c 编程 scanf 不会读取输入两次

标签 c scanf codeblocks

我正在用 C 语言在 CodeBlocks 中编写一个程序。我想检查输入的类型是否正确,如果不正确,请尝试再次获取它。

我的问题是,每当我尝试使用 scanf 获取输入并且输入不正确时,它都不会再次输入 scanf 并且只是继续循环,就好像输入总是不正确一样。

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

int main()
{
    float a = 0;

    while(scanf(" %f", & a) == 0)
    {
        printf("reenter");
    }

    printf("%f", a);

    return 0;
}

当我尝试输入错误的值“y”时,循环将继续:

enter image description here

如果我输入当前值,它会按预期得到它。

最佳答案

如果输入条目错误,scanf()不会消耗输入缓冲区,因此您必须以保证成功读取的方式额外读取它 - 例如作为字符串。

见下文:

int main()
{
    float a = 0;

    while (scanf(" %f", & a) == 0)
    {
        scanf("%*s"); // additional "blind" read

        printf("reenter");
    }

    printf("%f", a);

    return 0;
}

关于c 编程 scanf 不会读取输入两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294972/

相关文章:

c - "int *p =0;"和 "int *p; *p=0;"有什么区别

c - allegro - 如何绘制显示的有限部分

c - shell和C程序的关系

c - C scanf ("%c")函数一一读取字符的问题

C - union 输出到屏幕和文本文件

python - 如何在 Python 和 C 中使用三角函数在 GMP/MPFR 中获得非常高的精度?

c - fscanf 的不同输入类型

c - fscanf() 将什么放入 char 指针?

Python空闲。自动完成/显示完成不起作用

c++ - 在 C++ Win32 中哪个 Windows SDK 最适合我?