Clarification needed regarding getchar() and newline
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).
Raj
I am a Software Engineer interested in building scalable backend applications. I write about things I learn at work and side projects on https://www.soberkoder.com/.
Updated on June 11, 2022Comments
-
Raj almost 2 years
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 anewline
, and then the character'B'
, what will be stored inchar2
- 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?