-2

I'm writing a program that gets characters from the user using getchar and counts them. It's supposed to stop when the user enters EOF, print out the char count and print done. The code:

char cur = 0;
int count = 0;
while((cur = getchar()) != EOF){
    ++count;
}
printf("\n%d", count);
printf("\ndone\n");

However the loop doesn't stop until the user enters 2 consecutive EOF. I tried to force the loop to stop by by manually checking if the char is EOF and breaking the loop but it doesn't seem to work.

How can I make it stop after just one EOF?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

2

The getchar function is declared to return an int, not a char. Because you're assigning the result to a char, you won't be able to capture an EOF.

Change the datatype of cur to int.

EDIT:

This most likely has to do with how your terminal handles EOF. When I tested this, if I enter one or more characters on a line and then press CTRL-D, the characters (minus the CTRL-D) are sent to the program and read by getchar. If I press CTRL-D on a line by itself, even if I pressed ENTER to input the prior line, then EOF is detected.

If you were to redirect a file into the stdin of this program, you'd see that EOF is detected when the end of the file is reached.

dbush
  • 205,898
  • 23
  • 218
  • 273