6

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
Raj
  • 4,342
  • 9
  • 40
  • 45

4 Answers4

10

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

P.P
  • 117,907
  • 20
  • 175
  • 238
  • one little question: will getchar() simply flushed the data, take any space to save the LF? – Fuevo Oct 14 '19 at 12:01
  • @hikaru89 getchar() call simply returns the *value*. If it's not saved in the program (as the 2nd and 4th calls here), it's discarded and doesn't involve any additional storage. – P.P Oct 23 '19 at 21:15
0

I just want to know what the expected behavior is, and whether it depends on the compiler-dependent?

That's the expected behavior and not compiler-dependent.

You can use scanf to read A followed by newline, then B followed by newline. If you want to stick to getchar(), then simply give the input as AB.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
0

You can prevent reading newlines by explicitly testing for it. Instead of simply using

getchar():

you can use something like this

while((char1 = getchar()) == '\n');

If you're on windows you might want to test for '\r' too. So the code changes a little.

while((char1 = getchar()) == '\n' || char1 == '\r');
Peter F.
  • 111
  • 1
  • 7
-2

add statement fflush(stdin); in between statements. look this one

ch1=getchar();

fflush(stdin);
ch2=getchar();
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70
  • 8
    fflush() on an input stream is undefined behavior according to the C standard. It works on Windows, at least in Visual Studio, but should probably be avoided since it is non-standard. – Thomas Padron-McCarthy Sep 22 '12 at 13:48