c - 输入错误后如何刷新缓冲区

标签 c validation io int scanf

<分区>

我必须在输入中获取一个 int,以验证我写的:

 do {
    scanf("%d", &myInt);
    if (myInt >= 2147483648 || myInt <= -2147483648)
        printf("I need an integer between -2147483647 and 2147483647: ");
} while (myInt >= 2147483648 || myInt <= -2147483648);

但是如果我插入一个 char,它会以无限循环开始,但我会简单地验证 int 值。

最佳答案

使用scanf的返回值实现这一目标:

int myInt;
while (scanf("%d", &myInt) != 1) {
    // scanf failed to extract int from the standard input
}
// TODO: integer successfully retrieved ...

关于c - 输入错误后如何刷新缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19456978/

相关文章:

c - 字符到整数转换的巧妙之处

c - 为什么 -0x80000000 + -0x80000000 == 0?

c# - 自定义 StringLength 验证属性的客户端验证

c - 在我的 C 程序中遇到结构和数组问题

haskell - 将 Either a (IO b) 转换为 IO (Ei a b)

c - 从同一管道分两步读取

c - 读取文件时出现段错误

javascript - 提交前验证验证码

python - numpy数组用于范围内的浮点值

c - 在 Ubuntu 18.04 上编译 Python 3.7.4 时测试失败