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

2024-01-07

我想检查给定的输入是否是整数输入。我不想将输入存储在字符串中。在看到 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",有问题的输入保留在输入流中,下一个scanf在外while循环控制无法解析int again, a遗迹'\n', 重复。

  • 如果在从流中读取字符之前发生输入错误a, the 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。如果输入流损坏/关闭/过早结束,也会导致无限循环,例如如果您从空文件重定向标准输入。您可以让该循环也输出多个"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');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

scanf 的工作并检查输入是否为 int 的相关文章

随机推荐