I'm having a problem with a while loop. I have to enter a number which is bigger than 0 and below 81. when I use numbers like -1,0,1,2,82 it is going good and I get the expected result, but when I use a letter it keeps going through my while loop. I've used the debugger in eclipse and when I'm at the while loop amount is automatically set to '0' because of the failed scanf. Why does it keep looping when I insert a letter?

eclipseDebug

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

int main(){
    int amount = 0;
    printf("Give a number:\n");
    fflush(stdout);
    scanf("%d",&amount);
    while(amount <= 0 || amount >= 81){
        printf("Wrong input try again.\n");
        printf("Give a number:\n");
        fflush(stdout);
        scanf("%d",&amount);
    }
    return EXIT_SUCCESS;
}
有帮助吗?

解决方案

You need to make sure the scanf() worked. Use the returned value to do that

if (scanf("%d", &amount) != 1) /* error */;

When it doesn't work (because eg a letter was found in input) you probably want to get rid of the cause of the error.

A better option to get input from users is to use fgets()

其他提示

See this related question: scanf() is not waiting for user input

The reason is that when you press enter with a char, scanf failed and didn't eat up the char in the input feed. As a result, the next block begins having whatever you entered before.

You can check that by adding a getchar() before the scanf() inside the while loop. You'll notice that it'll repeat the while loop as many times as your line has invalid characters, then stop and wait for input. The getchar() ate one of the invalid chars in the input each time the loop ran.

It would be better not to use scanf like that, though. Take a look a this resource: Reading a line using scanf() not good?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top