Public Group

# Very Noob C Question

This topic is 2476 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Sorry, I'm sure I'm being very stupid, but could someone please clarify this for me (and delete the thread afterwards ) ?

In K&R, there's a program:
 int c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } 

Of course, I understand what it does and how to use it. What I don't understand is why the program doesn't terminate when an EOF is first reached. As far as I can see, the loop allows me to input a word (i.e. not a single character) by looping through the getchar() function until an EOF is reached. Otherwise it'll just take and output a single char, even if I enter a word or a phrase (only the first char of that word will be displayed). So the loop overcomes this "one char at a time" limitation of those functions. This I realize. But why on earth does it let me keep on entering words? I mean, why doesn't it terminate when an EOF is indeed reached and the loop execution condition becomes true? I don't get it. The loop should terminate upon displaying the first proper word I enter and the program execution should continue "downwards", meaning it should go to return 0. Instead, it sort of comes back to the line BEFORE the loop and enters the loop again, whereupon I can enter another word followed by EOF. And so on and so on.

I know I'm being a noob here, but why is that happening?

##### Share on other sites
An EOF isn't received after every word. A space returns a ' ' character.

##### Share on other sites

An EOF isn't received after every word. A space returns a ' ' character.

No, I meant EOF, as in the Enter key, not space.

What the program does is something like this:
"(empty cursor so I type:) one (I press enter)
(it displays) one (moves cursor to newline)
(again empty cursor so I type:) two (and press enter)
(it displays) two (moves cursor to newline)
....
..."

And so on. Until... nothing. It just keeps on going. I can enter words followed by enter infinitely.

##### Share on other sites
"Enter" is generally some combination of carriage return '\r' and line feed '\n'. It is totally distinct from EOF.

##### Share on other sites

"Enter" is generally some combination of carriage return '\r' and line feed '\n'. It is totally distinct from EOF.

Yes, exactly, thank you! EOF is Ctrl+Z on Windows. I'm sorry, should have googled it more properly.

I know the question is technically irrelevant, but since I've taken up C I wanna sort of know as much as possible about why stuff happens the way it does.

Sorry for taking your time.

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 16
• 12
• 20
• 12
• 19
• ### Forum Statistics

• Total Topics
632167
• Total Posts
3004527

×