Why is scanf() causing infinite loop in this code?

后端 未结 16 1439
日久生厌
日久生厌 2020-11-21 06:20

I\'ve a small C-program which just reads numbers from stdin, one at each loop cycle. If the user inputs some NaN, an error should be printed to the console and the input pro

16条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 06:59

    I had the same problem, and I found a somewhat hacky solution. I use fgets() to read the input and then feed that to sscanf(). 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 
    #include 
    #include 
    
    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) { // Exculude the sign charcters infront of numbers so the program can accept both negative and positive numbers
                    continue;
                }
                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;
    }
    

提交回复
热议问题