-1

The code below is printing "Menu" twice when input is different from 3.

do{
    puts("Menu");
    option = getchar();
}
while (option != '3');
rplaurindo
  • 1,277
  • 14
  • 23
  • 1
    Because of the trailing new line character maybe? – Captain Obvlious May 29 '15 at 22:21
  • 2
    It will print "Menu" every time it goes around that loop. What do you expect it to do? – GrahamS May 29 '15 at 22:22
  • @GrahamS forgiveness, friend. Maybe I was not very clear. But when the code is small so I think it's valid test it. The method "getchar" expects a key, but it comes after the puts ("menu"), then "menu" has already been printed once, but if I press 3 and "enter", even on the first run of the line "option = getchar ()", "menu" is printed again, but should not, should just test the" while "and exit the loop. – rplaurindo May 31 '15 at 13:25
  • @Rafael: no problem. It wasn't clear from the question what you thought the issue was. What you are really asking is: "Why does it go round the loop twice when you enter a character that is not '3' ?" You could find the answer by looking at the value of `option` in your debugger on each iteration of the loop. If you don't have a debugger then you could add a `putchar(option)`. As others have answered, when you enter something `getchar` will get the character on the first iteration and then the newline character on the second. – GrahamS May 31 '15 at 13:40
  • @GrahamS I have no debugger. So thank you for the tip of the use of "putchar ()". – rplaurindo May 31 '15 at 14:51

2 Answers2

3

You just need to flush your stdin. When your program reaches getChar, it finds the newline character, and processes it as an input character.

if your not set on using getChar() to retrieve the input a better option would probably be to use std::cin, as it deals with white space such as this more intelligently

You can also flush the input by adding the line fseek(stdin,0,SEEK_END); right before you retrieve the character from the input.

or you can run an if statement to check if the character retrieved is newline

if ( option != '\n' ) {
 ...
}

also see this answer Using getchar() on c gets the 'Enter' after input

Community
  • 1
  • 1
Austin Philp
  • 94
  • 1
  • 10
3

A quick fix:

do{ puts("Menu"); std::cin >> option; } while (option != '3');

Karskrin
  • 91
  • 2