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