I've been reading "The C Programming Language" and I got to this part of inputs and outputs.
I've read other threads saying that the console doesn't recognize enter as EOF
. So that I should use CTRL + Z in Windows or CTRL + D in Unix (neither of those is working for me).
I also read other people asking the same saying they could make it work, the problem in their codes was syntax not the program not terminating.
Is there another solution?
This is the code:
#include <stdio.h>
main()
{
int nb, nl, nt, c;
nb = 0;
nl = 0;
nt = 0;
while ((c = getchar()) != '\n') {
if (c == ' ')
++nb;
else if (c == '\n')
++nl;
else if (c == '\t')
++nt;
}
printf("Input has %d blanks, %d tabs, and %d newlines\n", nb, nt, nl);
}
Edit: The \n
was supposed to be an EOF, I was messing around before I posted and I forgot I changed it :P
It doesn't work with EOF
neither, I just skipped that one.
If the stream is at end-of-file, the end-of-file indicator is set, and getchar() returns EOF. If a read error occurs, errno is set, and getchar() returns EOF.
getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the most basic input function in C.
EOF is End Of File. When we input a character to getchar(), that will be compared with the EOF, and if the input is matching(equal) to that of EOF it will print 1 or else(unequal) it will print 0.
The End of the File (EOF) indicates the end of input. After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.
while ((c = getchar()) !=EOF) {
}
Then use Ctrl+Z or F6 on Windows
Following will wait for either a \n
or EOF
, which comes first
while((c = getchar()) != '\n' && c != EOF){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With