c - 为什么这个例子在C中陷入了无限循环?

标签 c infinite-loop goto

在下面的示例中,如果我在 Mac OS X 终端中输入一个字符,程序将陷入无限循环,打印 Please enter a number:一行一行,并且不允许用户输入任何内容。这段代码有什么问题?解决方法是什么? 我想更改代码,如果未输入数字,则会提示用户错误消息并要求重新输入数字。

#include <stdio.h>

int main(int argc, const char * argv[]) {

    int number = 0, isnumber;
    getagin: printf("Please enter a number:\n");
    isnumber = scanf("%i", &number);
    if(isnumber) {
        printf("You enterd a number and it was %i\n", number);
    } else {
        printf("You did not eneter a number.\n");
        goto getagin;
    }

    return 0;
}

编辑:我在阅读建议后编辑了代码,并修复了无限循环问题。对于无限循环问题来说,这并不是一个糟糕的解决方案,通过一个简单的 for 循环,我告诉 C 搜索任何非数字字符。下面的代码不允许像 123abc 这样的输入.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, const char * argv[]) {

    char line[10];
    int loop, arrayLength, number, nan;
    arrayLength = sizeof(line) / sizeof(char);
    do {
        nan = 0;
        printf("Please enter a number:\n");
        fgets(line, arrayLength, stdin);
        for(loop = 0; loop < arrayLength; loop++) { // search for any none numeric charcter inisde the line array
            if(line[loop] == '\n') { // stop the search if there is a carrage return
                break;
            }
            if((line[0] == '-' || line[0] == '+') && loop == 0) {
                continue;
            } // Exculude the sign charcters infront of numbers so the program can accept both negative and positive numbers
            if(!isdigit(line[loop])) { // if there is a none numeric character then add one to nan and break the loop
                nan++;
                break;
            }
        }
    } while(nan || strlen(line) == 1); // check if there is any NaN or the user has just hit enter
    sscanf(line, "%d", &number);
    printf("You enterd number %d\n", number);
    return 0;
}

最佳答案

输入非数字时出现无限循环的原因是缓冲区中留下的非数字字符,因为 scanf 不会在下次读取 时读取该字符。 scanf (因为它与格式说明符不匹配)。在下一次迭代中 scanf 再次找到该字符,但不读取它并立即退出。这种情况会反复发生,并且您将陷入无限循环。放置一个 while(getchar() != '\n'); 语句来使用该字符。

试试这个

#include <stdio.h>

int main(int argc, const char * argv[]) {

    int number = 0, isnumber;
    getagin: printf("Please enter a number:\n");
    isnumber = scanf("%i", &number);
    if(isnumber) {
        printf("You enterd a number and it was %i\n", number);
    } else {
        printf("You did not eneter a number.\n");
        while(getchar() != '\n'); // T consume all non-digits
        goto getagin;
    }

    return 0;
}

关于c - 为什么这个例子在C中陷入了无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829672/

相关文章:

c - 在 C 中打印十六进制的前导零

c - 使用 strdup 进入 malloc 保留空间

c++ - C 和 C++ 中的指针和动态内存

c - 如何实现无限循环

c - 如果标 checkout 现在 goto 语句下面,那么 goto 如何找到标签的地址?

c - 使用 TinyCC 编译时使用 Intel ASM 语法

Python,预期无限循环

perl - 为什么这不会永远运行?

iphone - 如何在 Objective-C 的 switch 语句中使用 goto?

c++ - 有没有办法不使用 goto 来编写这样的程序?