Reputation: 31221
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
Reputation: 46027
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;
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
Reputation: 96109
enter
is not EOF on a console it is either ctrl-Z (windows) or ctrl-D (unix)
Upvotes: 0
Reputation: 132994
If you're under windows, press Ctrl
+Z
and then enter. If under linux, press Ctrl
+D
. That will cause end of file.
Upvotes: 0
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