gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:08:36 30 4
gpt4 key购买 nike

我正在用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com