c - scanf() 在 c 中使用两个输入进行验证

标签 c

这是c代码:

int main()
{
    int return_val = 0;
    int a = 0;
    int b = 0;

    while(1)
    {
            printf ("Enter two integers:\n");
            return_val = scanf("%d %d", &a,&b);

                    if (return_val == 1)
                    {
                            break;
                    }

            printf("Invalid\n\n");

            while (getchar() != '\n');
    }
    return 0;
}

程序需要获取两个整数并验证它们是否都是整数。现在我有以下错误的输出。

Enter two integers:
f f
Invalid

Enter two integers:
2 3
Invalid

Enter two integers:

我的程序只需一个输入即可运行。如果我改变

return_val = scanf("%d %d", &a,&b);

return_val = scanf("%d", &a);

然后就可以了。

那么如何一起验证两个输入?

最佳答案

scanf 返回它获得的输入数量。

所以,

scanf("%d %d",&a,&b);

始终返回 2,因为它获取 2 个值作为输入。所以你的条件总是失败。

如果您提示输入 2 个输入,则在获得 2 个输入后执行下一行。因此,您必须检查两个输入是否都是整数

关于c - scanf() 在 c 中使用两个输入进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28306460/

相关文章:

c - LittleCMS 库 : which type of variable do I have to use during conversion from rgb (bgr) to cmyk colors

c - GDB重置配置

C 声明顺序错误

c - 我的多线程应用程序的逻辑?

c - 二维数组的问题

c - 在 Objective C 中使用 C 结构

c - 未定义对 `pow' 和 `floor' 的引用

c - 取消引用指向下一个值的指针时出错

c - 如何使用套接字传输pdf、mp3或mp4文件?

c - C 中的 Trie : Pointer detected as null. 导致内存泄漏