-1
#include <stdio.h>

int main(void)
{

    char ch;
    int count;

    while((ch=getchar())!=EOF){
        if(ch==' '){
           count++;
        }
    }
    printf("total words is %d",count);
    return 0;
}

my C code is here ,I am confused where I put ctrl+Z directly in windows ,it turn out count is 2?why it go loop for two and where comes the space?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
a86356
  • 121
  • 7

1 Answers1

4

The biggest issue here is, you've left count uninitialized. So, whether the if is success or not, you'll end up reading a unitialized local variable which invokes undefined behavior.

You should always initialize the local variables, like

 int count = 0;

That said, getchar() returns an int. Storing that into a char is wrong because in case the function returns EOF (as you expect here), it'll not fit into a char.

Regarding EOF marco, quoting C11, chapter §7.21.1

EOF
which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

So, you should change the type of ch from char to int, like

int ch = 0;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261