简体   繁体   English

字符输入导致C中的无限循环

[英]Character entry causing infinite loop in C

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 . 好的,所以我搜索了几个地方以获得答案,我在C++找到了相同问题的答案,但它涉及清除cin和那些东西,我不知道如何将其转换为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. 另外,请记住,我基本上是在教自己C ,除了您在此代码中看到的内容之外,我不太了解。

Basically, my problem is this: I am running a loop that asks for input and then uses a switch statement to choose what happens. 基本上,我的问题是:我正在运行一个循环,要求输入,然后使用switch语句来选择会发生什么。 The switch takes an int , and it works fine with any numerical entry. switch采用int ,它适用于任何数字输入。 When you enter a char , however, it just loops infinitely, giving no chance to input anything else. 但是,当你输入一个char时,它只是无限循环,没有机会输入任何其他东西。

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. 假设这是与C++示例中的问题相同,我查了一下 - 我不是百分之百确定它是 - 当我输入一个char它会被添加到缓冲区,并且永远不会被清除,所以每次它都循环无效输入再次使用。 Clearing the buffer seemed simple enough in C++ , but I was unable to find anything I could understand in C . C++清除缓冲区似乎很简单,但我无法在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 :P

fflush(stdin) has undefined behavior. fflush(stdin)有未定义的行为。 If you want to discard characters entered after the scanf() call, you can read and discard them. 如果要丢弃在scanf()调用后输入的字符,可以阅读并丢弃它们。
You can use getchar() to clear the character. 您可以使用getchar()来清除角色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM