0

Can anyone please tell me why the printf statement is getting executed 2 times ?

do {

    printf("\n Enter the choice: a to add, d to display, q to exit: ");
    scanf("%c",&choice);

    switch(choice) {
        case 'a':
            addData();
            break;

        case 'd':
            display();
            break;
    }
} while (choice != 'q'); 

I am expecting the following:

Enter the choice: a to add, d to display, q to exit: a Enter the choice: a to add, d to display, q to exit: d

But I am getting the following:

Enter the choice: a to add, d to display, q to exit: a Enter the choice: a to add, d to display, q to exit: Enter the choice: a to add, d to display, q to exit: d

Can anyone please let me know, what is the issue behind the middle line ?

Thanks, Meghdeep

  • Where is addData() and display() function? – yash Jan 27 '17 at 11:13
  • 1
    When you write the first input, you press the `Enter` key on the keyboard, right? That key is put into the `stdin` input buffer as a newline. After the character you gave as input has been read, the next character is that newline, and you will read that in the next iteration of the loop. If you had stepped through the code in a debugger it would have been *very* obvious. Next time please do that first. – Some programmer dude Jan 27 '17 at 11:14
  • Always a bug: not testing the return value from scanf. – Jens Jan 27 '17 at 11:15
  • Do not completely solve the problem. If I add %c%*c, the option next options which are to be repeated within the do while block is not getting executed. So, whats the correct way to get rid of this problem while making sure that the do while block continues to work ? Finally got it working with `scanf(" %c",&choice);` – Meghdeep Basu Jan 27 '17 at 11:21

0 Answers0