gpt4 book ai didi

c - scanf 的工作并检查输入是否为 int

转载 作者:行者123 更新时间:2023-12-05 01:31:20 25 4
gpt4 key购买 nike

我想检查给定的输入是否为整数输入。我不想将输入存储在字符串中。在看到关于 stackoverflow 的几个问题并通过点击和试用后,我创建了以下代码

while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
if(a == '\n')
scanf("%c",&a);
else
{
while(a != '\n')
scanf("%c",&a);
}
}

它有效,但根据我的理解,以下应该也有效

while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
while(a != '\n')
scanf("%c",&a);
}

有人可以告诉我为什么上面没有工作吗??另外,如果有人有更好的解决方案,请也提供。

注意:我将 12qwe 也视为无效输入。我只想要整数。

最佳答案

问题

while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
while(a != '\n')
scanf("%c",&a);
}

是如果 a 在扫描之前恰好包含 '\n',并且扫描失败,则内部 while 循环不会'根本不要跑。所以

  • 如果扫描尝试从输入流中解析 int 失败,因为输入是例如"ab c\n",有问题的输入保留在输入流中,外层 while 循环控制中的下一个 scanf 无法解析 int 一次,a 仍然是 '\n',重复。

  • 如果在将字符从流中读取到a 之前发生输入错误,则由于流已损坏,外循环控制中的scanf 将失败,重复.

在另一个版本中,

while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
if(a == '\n')
scanf("%c",&a);
else
{
while(a != '\n')
scanf("%c",&a);
}
}

只要有要从流中读取的输入,您就至少取得了一些进展,因为无论 a 包含什么,在尝试下一次解析之前,您至少从输入流中读取了一个字符一个 int。如果输入流损坏/关闭/过早结束,它也会导致无限循环,例如如果您从空文件重定向 stdin。您可以让该循环还输出多个 "Please enter an integer only : " 消息,方法是提供类似 `"a\nb\nc\nd\n"的输入。

因此,在从输入转换任何内容之前,您应该检查 scanf 是否遇到流的末尾或其他读取错误,并在这种情况下中止:

int reads;
while(((reads = scanf("%d%c", &num, &a)) != 2 && reads != EOF) || a != '\n')
{
printf("Please enter an integer only : ");
// read at least one character until the next newline
do {
reads = scanf("%c", &a);
}while(reads != EOF && a != '\n');
}

关于c - scanf 的工作并检查输入是否为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13049893/

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