Toni Ivanov
Toni Ivanov

Reputation: 81

How getchar() works when it is used as condition in while loop

I cant understand how the following code really works.

int main() {

char ch;

while((ch=getchar())!='\n')
{
    printf("test\n");
}

return 0;

}

Lets say we give as an input "aaa". Then we get the word "test" as an output in 3 seperate lines.

Now my question is, for the first letter that we type, 'a', does the program goes inside the while loop and remembers that it has to print something when the '\n' character is entered? Does it store the characters somewhere and then traverses them and executes the body of the while loop? Im lost.

Upvotes: 3

Views: 929

Answers (2)

Frankie_C
Frankie_C

Reputation: 4877

What you see is due to the I/O line buffering.

The getchar() functions doesn't receive any input until you press the enter. This add the \n completing the line.

Only at this point the OS will start to feed characters to the getchar(), that for each input different from \n prints the test message.

Apparently the printout is done together after you press the enter.

You can change this behavior by modifying the buffering mode with the function setvbuf(). Setting the mode as _IONBF you can force the stream as unbuffered, giving back each character as it is pressed on the keyboard (or at least on an *nix system, MS is not so compliant).

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409176

There are many layers between the user writing input into a terminal, and your program receiving that input.

Typically the terminal itself have a buffer, which is flushed and sent to the operating system when the user presses the Enter key (together with a newline from the Enter key itself).

The operating system will have some internal buffers where the input is stored until the application reads it.

Then in your program the getchar function itself reads from stdin which is usually also buffered, and the characters returned by getchar are taken one by one from that stdin buffer.


And as mentioned in a comment to your question, note that getchar returns an int, which is really important if you ever want to compare what it returns against EOF (which is an int constant).

And you really should compare against EOF, otherwise you won't detect if there's an error or the user presses the "end-of-file" key sequence (Ctrl-D on POSIX systems like Linux or macOS, or Ctrl-Z on Windows).

Upvotes: 3

Related Questions