Reputation: 1650
I'm a middle experienced Java developer and have many problems learning the C language for my computer science study. I try it with the book "The C Programming Language" which many people seem to recommend.
But I've got problems with the simplest stuff like the EOF in combination with getchar(). Here's the code:
#include<stdio.h>
main()
{
int i = 0;
while (getchar() != EOF)
{
++i;
printf("Count of characters is %d", i);
}
}
I'm working with Mac OS X Lion and use the "cc" command with "./a.out" for running in terminal, like described in the book to run the file. And what I get is:
I really have no idea what could be the issue. Can someone help?
Upvotes: 1
Views: 930
Reputation: 5775
When you type a character, such as "6" and you click enter (which is equal to \n), then the command "6\n" is sent, so it is 2 characters. If you just press enter, then 'i' will be increased by 1.
The EOF means end of file and its equivalent to ctrld+D. It is useful if you read a text file. Else it is the same as saying "Forever".
Upvotes: 0
Reputation: 182649
Always counting one character too much
That could be the newline (enter / return).
the while loop never ends! it just waits for another input after reaching end of input
You are likely not signaling end of input. You should be using CTRL-D
to do so.
Upvotes: 4