为什么此示例卡在C的无限循环中? [英] Why this example is stuck in an infinite loop in C?

查看:79
本文介绍了为什么此示例卡在C的无限循环中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,如果我在Mac OS X终端中输入字符,则程序将陷入无限循环,逐行打印Please enter a number:,并且永远不允许用户输入任何内容.此代码有什么问题?解决办法是什么? 我想以一种方式更改代码,如果未输入数字,则提示用户输入错误消息,并要求其再次输入数字.

In the example below, if I enter a character in Mac OS X terminal, the program will get stuck in an infinite loop, printing Please enter a number: line after line and never allowing the user to input anything. What's wrong with this code? What is the fix? I want to change the code in a way that if a number is not entered, the user is prompted with an error message and asked to enter a number again.

#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.

I edited the code after reading the suggestions, and fixed the infinite loop problem. This is not a bad fix for the infinite loop problem, and with a simple for loop I tell C to search for any none numeric character. The code below won't allow inputs like 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再次找到该字符并且不读取它并立即退出.这种情况反复发生,您将陷入无限循环.放置while(getchar() != '\n');语句以使用此字符.

The reason that you are getting infinite loop on entering a non-digit is the non-digit character left in the buffer as it is not read by the scanf for the next read of scanf (as it doesn't matches the format specifier). on next iteration scanf again finds this character and do not read it and exit immediately. This happens repeatedly and you are getting an infinite loop. Place a while(getchar() != '\n'); statement to consume this character.

尝试一下

#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的无限循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆