Bali C
Bali C

Reputation: 31221

No output on console

I am just starting to learn C, this is probably a very easy question for you guys but your help is very appreciated. I am trying to use this code to count the number of characters inputted into the console but when I hit enter it just gives me a blank new line, like printf hasn't worked. Where am I going wrong?

int c, number;
while((c = getchar()) != EOF){
++number;
}
printf("%d\n", number);

Thanks.

Upvotes: 2

Views: 203

Answers (4)

taskinoor
taskinoor

Reputation: 46027

  1. Enter is not EOF as already pointed by other answers.
  2. After inputting EOF you will get wrong result as you have not initialized number. You are incrementing garbage value. Initialize it to zero.

    int c, number = 0;

  3. In this way newlines will also be counted. If you want to skip them then you need to test that c is not equal to '\n' before incrementing number.

Upvotes: 1

Martin Beckett
Martin Beckett

Reputation: 96109

enter is not EOF on a console it is either ctrl-Z (windows) or ctrl-D (unix)

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

If you're under windows, press Ctrl+Zand then enter. If under linux, press Ctrl+D. That will cause end of file.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363547

When you hit enter, the program increments the counter because it gets a newline character and waits for more input. You have to feed the program an EOF with Ctrl+D (Linux, Unix, Mac) or Ctrl+Z, Enter (Windows).

Upvotes: 6

Related Questions