虽然表达式变得虚假,但是循环不会退出

时间:2014-11-07 16:38:19

标签: c switch-statement break do-while

我这里有一个程序,其中包含指定void方法中的do-while循环。我试图退出函数中的循环,以便do-while循环实际上按预期工作。除了在我运行程序并且其中一个案例发生之后,程序继续运行,尽管我的while语句声明它应该只在(userInput!= 1)时工作。 我不能使用全局变量来解决这个问题,因为我的任务限制了我使用这些技术,所以任何帮助都会非常感激!

以下是我的代码片段:

void functionTest()
{
    int gameOver = 0;
    int userInput;

    do
    {
        printf("please enter a number 1-3");
        scanf("%d",&userInput);

        switch(userInput)
        {
            case 1:
               printf("You entered %d",userInput);
               gameOver = 1;
               break;

            case 2:
               printf("You entered %d",userInput);
               gameOver = 1;
               break;

            case 3:
               printf("You entered %d",userInput);
               gameOver = 1;
               break;
        }
    }
    while(gameOver!= 1);
}
}

2 个答案:

答案 0 :(得分:0)

问题可能在于您使用scanf()时。你在输入之前输入的东西不是1,2或3.当你要求你输入一个选择时,你能告诉我们你输入的确切内容吗?

有时,在使用新的scanf()之前,需要刷新标准输出。在scanf行之前尝试fflush(stdout)。 请参阅older question 1older question 2

编辑: 如果我输入除#34; 1"," 2"之外的任何内容,我可以轻松地重现问题。或" 3" ...

我建议你在执行switch语句之前执行以下操作:

  1. 在scanf()
  2. 之前添加fflush(stdout)
  3. 接受输入为字符串(%s)而不是数字。 (char []需要)
  4. 修剪尾随和前导空格的字符串。
  5. 使用库函数转换为数字
  6. 然后基于该号码切换案例

答案 1 :(得分:0)

问题是如果在读取整数之前输入流中存在其他字符(不是整数的一部分),则scanf()会失败并且永远不会清除不可用的数据。导致无限循环(其中scanf()反复无法读取相同的字符作为整数,一遍又一遍)。

因此,当scanf()失败或作为格式的一部分时,您需要读取无效字符。

一个简单的解决方法是从以下位置更改您的scanf:

scanf("%d",&userInput);

为:

scanf("%*[^0-9]%d",&userInput);

在读取整数之前读取(并丢弃)输入流中不是数字0-9的任何字符...但是仍然没有检查scanf是否因任何其他原因而失败(如一个封闭的输入流)。

您可以用以下内容替换它:

int scanfRes,c;
do {
    scanfRes = scanf("%d",&userInput); /* try to read userInput */
    /* ..then discard remainder of line */
    do {
        if ((c = fgetc(stdin)) == EOF)
            return; /* ..return on error or EOF */
    } while (c != '\n');
} while (scanfRes != 1); /* ..retry until userInput is assigned */

..在分配字段之前将重试scanf(),在每次尝试后丢弃该行的其余部分,并在fgetc()遇到错误或EOF时退出该函数。