1

I have a VS 10 console application,which has to take two char inputs and make some processing based on their values.I wrote the following code:

char c1,c2;
printf("Ener c1:");
c1 = getChar();
//Some desicion is made based on c1
printf("Ener c2:");
c2 = getChar();
//Some desicion is made based on c2

Run it with :

Ener c1:y
Ener c2:S

After this execution the value of c1 is 'y' and the value of c2 is '\n' How can it be solved?

YAKOVM
  • 9,805
  • 31
  • 116
  • 217

2 Answers2

2

When you get a single char from cin, the user technically presses the character: 'y' then enter, or '\n'.

The \n is in the buffer, so you should flush the buffer after the first getchar to remove the \n. Try using cin.ignore();

PS: I'd read this instead and rethink what you're doing:

How do I flush the cin buffer?

Community
  • 1
  • 1
John Humphreys
  • 37,047
  • 37
  • 155
  • 255
1

When you entered 'y' and pressed enter, your application received 2 characters, it received 'y' and '\n' (the enter key. A simple solution would be to loop until you have another char than \n or EOF :

while ((c2 = getchar()) != '\n' && c != EOF);
jValdron
  • 3,408
  • 1
  • 28
  • 44