Question

Ok, so I've searched several places for an answer to this, and I found the answer to the same problem in C++, but it involved clearing cin and that stuff, and I'm not sure how to translate that to C. I apologize in advance if this was, in fact, answered somewhere else, and I just missed it. Also, keep in mind that I'm basically teaching myself C, and I don't know much beyond what you see in this code.

Basically, my problem is this: I am running a loop that asks for input and then uses a switch statement to choose what happens. The switch takes an int, and it works fine with any numerical entry. When you enter a char, however, it just loops infinitely, giving no chance to input anything else.

Assuming this is the same problem as it was in the C++ examples I looked up - and I'm not 100% sure it is - when I enter a char it gets added to the buffer, and never gets cleared, so each time it loops the invalid input gets used again. Clearing the buffer seemed simple enough in C++, but I was unable to find anything I could understand in C.

Here's my code, for reference:

int main()
{


  while(1)
  {
    printf("(1-10) -> Run a program | (-1) -> Display menu | (0) -> Quit : ");

    int quit = 0;
    int select;
    scanf("%d", &select);
    switch(select)
    {
      case 1:
        printf("%s", pgmRun);
        helloWorld();
        printf("%s", pgmEnd);
        break;

      //More cases here

      case 0:
        quit = 1;
        break;
      default:
        printf("\n");
        printf("Error: Invalid input\n");
        printf("\n");
    }

    if(quit == 1)
      break;
  }
return 0;
}

Thanks in advance for your help, and sorry for such a lengthy post. I tend to be long-winded. :P

Was it helpful?

Solution

fflush(stdin) has undefined behavior. If you want to discard characters entered after the scanf() call, you can read and discard them.
You can use getchar() to clear the character.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top