c - 如何让我的代码免于进入无限循环?

标签 c loops infinite

我正在重写“C Programming for Absoulute Beginners”中的猜谜游戏代码,以使用 isdigit() 函数验证用户是否输入了数字。

代码的其余部分在错误检查方面有效;但是一旦用户输入非数字,代码就会进入无限循环。

#include <stdio.h>
#include <stdlib.h>

#define NO 2
#define YES 1

main()

{
    int guessGame;    
    guessGame = 0;

    int iRandomNum = 0;
    int iResponse = 0;

    printf("\n\nWould you like to play \"The Guessing Game\"?\n\n"); 
    printf("\nType '1' for Yes or '2' for No!\n\n"); 
    scanf("%d", &guessGame);

    do{
        if(guessGame == YES){
            iRandomNum = (rand() % 10) + 1;

            printf("\nGuess a number between 1 and 10:\n\n ");
            scanf("%d", &iResponse);

            if(!isdigit(iResponse)){
                printf("\nThank you\n");
                printf("\nYou entered %d\n", iResponse);
                if(iResponse == iRandomNum){
                    printf("\nYou guessed right\n");
                    printf("\nThe correct guess is %d!\n", iRandomNum);
                    printf("\nDo you wish to continue? \n");
                    printf("\nType '1' for Yes or '2' for No!\n\n");
                    scanf("%d", &guessGame);

               } else {
                    printf("\n\nSorry, you guessed wrong\n");
                    printf("\nThe correct guess was %d!\n", iRandomNum);
                    printf("\n\nDo you wish to continue? \n");
                    printf("\nType '1' for Yes or '2' for No!\n\n");
                    scanf("%d", &guessGame);

                }
            }
            else {
                printf("\nYou did not enter a digit\n");
                printf("\n\nPlease enter a number between 1 and 10:\n\n");
                scanf("%d", &iResponse);
            }
        }
        else {
            printf("\nThe window will now close. Try again later!\n");
            exit(0);
        }
    }while(guessGame != NO);
}

最佳答案

代码进入无限循环,因为 scanf() 无法读取整数。您输入的字符保留在键盘缓冲区中。只要该字符存在于缓冲区中,就不可能再读取整数。 scanf() 每次只返回读取为 0 的项目数。因此,程序不会等待用户输入数据和无限循环结果。

scanf() 返回成功读取的项目数。因此,您可以简单地检查 scanf() 的返回值,如果返回值为 1,则 scanf() 已正确读取整数。

   check = scanf("%d", &iResponse);

   if(check == 1){
        printf("\nThank you\n");
        printf("\nYou entered %d\n", iResponse);

如果输入错误则刷新缓冲区

        else {
            while (getchar() != '\n');  //flush the buffer
            printf("\nYou did not enter a digit\n");
            printf("\n\nPlease enter a number between 1 and 10:\n\n");
            //scanf("%d", &iResponse);
        }

这里不需要要求输入,while循环会继续并在开头提示输入

关于c - 如何让我的代码免于进入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40274218/

相关文章:

c - 第二个 printf 不工作,需要帮​​助。 (C郎)

php - 递归循环创建家谱? (PHP/MySQL/HTML)

loops - Handlebars : Get index of an item when there are two rows of items

java - HashMap.put 在 Java 中导致无限循环

python - 条件避免无限python pandas的划分过程

c - 使用 pthread 创建线程失败

无法理解此代码堆栈存储函数调用 c 的输出

统计单词出现次数

Javascript while 或 for 循环更改字符串直到满足条件

list - Haskell 惰性求值和带有无限列表的 let-in 表示法