简体   繁体   中英

Checking if the user entered an int - C

I need to check if the user entered a integer in a scanf() (in C). I have this code:

do {
    srs = scanf("%d", &x);
} while (!srs);

If I enter a number it works and continues with the program, but if I enter a char, it just asks me for input again. Though, if then of this I enter a correct integer, it don't break the loop.

When you don't enter the number first, it leaves the non-numeric character on the input stream for the next call to pick up. So you get in an infinite loop.

You should be using fgets to read a whole line of input, then sscanf on that input line.

do {
    char line[512];
    fgets(line,512,stdin);
    srs = sscanf(line,"%d", &x);
} while (!srs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM