Reputation: 21
It's my first time posting here, so hopefully this goes as intended.
I'm doing one of the early exercises from K&R. The objective is to use getchar() to get a bunch of characters from the user, and then print them using putchar(), but skipping any extra spaces. My solution to the exercise works great, but I don't understand why.
Here's the program:
#include <stdio.h>
int main()
{
int c, spc;
c = 0;
spc = 0;
while(c != EOF)
{
c = getchar();
if(c == ' ')
{
if(spc != 1)
{
putchar(c);
spc = 1;
}
}
if(c != ' ')
{
spc = 0;
putchar(c);
}
}
return 0;
}
There is only one loop, and execution stops during the first iteration when it hits getchar() as expected. Once carriage return is pressed, the program proceeds to print out whatever the user typed into the buffer, sans extra spaces - exactly what it's supposed to do.
But what I don't understand is why execution doesn't stop with each subsequent iteration of the loop when it comes across getchar(). Does the /n character have something to do with it? I did notice that it also prints the newline, and after every thing is printed it again stops at getchar(). So, why is it skipping over getchar() at the start of each iteration while printing everything in the buffer?
I've been toying with C for a long while, but only recently have made an effort to learn it the 'right' way. Since I have some experience you don't have to dumb your answers down too much (so, like you're explaining it to a 10 year old instead of a 5 year old).
Upvotes: 2
Views: 1456
Reputation: 3045
while (c != EOF)
ends after hitting EOF
. Try pressing Ctrl + D
after some input.
Upvotes: 0
Reputation: 182619
When you type stuff and you hit enter, everything is stored in an internal buffer. So every time the loop executes, it hits getchar
who *does * go to that buffer and pulls a single character.
But what I don't understand is why execution doesn't stop with each subsequent iteration of the loop
The program stops only in the event where getchar
doesn't find anything in that buffer.
Now \n
has nothing special in this case. It's just the convention that the CLI doesn't actually "send" what you type to the program until you hit return (i.e. you can hit backspace and so on).
Upvotes: 4