Question

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?

Was it helpful?

Solution

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?

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top