Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while ((c = getchar()) != EOF) Not terminating

Tags:

c

eof

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.

like image 481
user2738586 Avatar asked Sep 02 '13 04:09

user2738586


People also ask

Can Getchar return EOF?

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.

What does getchar () do in C?

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.

What would the expression C Getchar EOF do?

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.

How do you cancel EOF?

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.


1 Answers

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){

}
like image 82
P0W Avatar answered Sep 22 '22 10:09

P0W