Clarification needed regarding getchar() and newline

15,390

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).

Share:
15,390
Raj
Author by

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, 2022

Comments

  • Raj
    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 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?