Clarification needed regarding getchar() and newline

Raj picture Raj · Sep 22, 2012 · Viewed 13.3k times · Source

I have a doubt regarding using getchar() to read a character input from the user.

char char1, char2;
char1 = getchar();
char2 = getchar();

I need to get 2 chars as inputs from the user. In this case, if the user enters the character 'A' followed by a newline, and then the character 'B', what will be stored in char2 - will it be the newline character or the character 'B'?

I tried it on CodeBlocks on Windows, and char2 actually stores the newline character, but I intended it to store the character 'B'.

I just want to know what the expected behavior is, and whether it is compiler-dependent? If so, what differences hold between turbo C and mingW?

Answer

P.P picture P.P · Sep 22, 2012

Yes, you have to consume newlines after each input:

char1 = getchar();
getchar(); // To consume `\n`
char2 = getchar();
getchar(); // To consume `\n`

This is not compiler-dependent. This is true for all platforms as there'll be carriage return at the end of each input line (Although the actual line feed may vary across platforms).