Hello! I want to know why infinite loops occur.

Asked 1 years ago, Updated 1 years ago, 83 views

Hello! I fell into an infinite loop while practicing c, but I can't solve it.

Here's the situation.

If you receive an integer between 1 and 10, you have to exit the for statement and re-enter it when you receive other numbers.

Below is the code you created.

int testcase;
for (;;) {
    testcase = 0;
    printf("enter the number of testcase : ");
    scanf_s("%d", &testcase);
    if (testcase > 10 || testcase < 1) {
        printf("wrong number. please enter a number between 1 and 10 in integer type. \n");
    }
    else {
        break;
    }
}

The problem here is that if you enter a number or character with a decimal place outside the range,

printf("wrong number. please enter a number between 1 and 10 in integer type. \n");

The sentence keeps running.

I don't know why an infinite loop occurs even if I observe what value the variable testcase has according to the input in debugging mode.

Please give us a lot of suggestions! Thank you (__)

c scanf for

2022-09-22 18:05

1 Answers

This is caused by the fact that the incorrect values received through scanf continue to remain in the input stream and mess with! To solve the problem, empty the input stream properly.

It's a very annoying bug when you first encounter it.

Anyway, please refer to the code below. The added line is a line of while (getchar()!='\n') {} to empty the input stream. Of course, this code is just an example, and there are many other good ways :3

 

#include <stdio.h>

int main(void) {
    int testcase;

    while (1) {
        testcase = 0;
        printf("enter the number of testcase : ");
        scanf_s("%d", &testcase);

        if (testcase > 10 || testcase < 1) {
            while (getchar()!= '\n') {} // empty input stream
            printf("wrong number. please enter a number between 1 and 10 in integer type. \n");
        }

        else {
            break;
        }
    }
}


2022-09-22 18:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.