c - 输入验证 : checking multiple values

标签 c validation input

用户只有“a”或“b”两个选择,如果用户输入不是“a”或“b”,则错误消息应提示他们仅输入“a”或“b”。

优点: 我输入字母“a”,它绕过了 while 循环。

坏处: 当我输入“b”时,它不会绕过 while 循环吗?

有什么解决这个问题的建议吗?

#include <stdio.h>
int main(void)
{
    char c;

    printf("enter a or b to make it out!\n");

    //loop if answer is NOT a or b
    while ((c = getchar() != 'a') && (c = getchar() != 'b'))
    {
        //let the user know there has been a problem!
        printf("That value is invalid");
        printf("\nPlease enter a or b:\n");
        fseek(stdin,0,SEEK_END);
    }

    printf("You made it out!");
    return 0;
}

最佳答案

每当您执行 getchar() 时,都会读取一个_不同的_字符。所以你应该将 while 循环更改为

while (((c = getchar()) != 'a') && (c != 'b'))

否则,每当检查条件 c = getchar() != 'b' 时,c 将为 \n

此外,您应该将 \n 移开。因此,您可以在 while 循环中添加另一个 getchar(),您不需要使用其返回值。

关于c - 输入验证 : checking multiple values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40709986/

相关文章:

html - 如何在 HTML 文本输入字段中隐藏插入符号?

c - 如何将用户输入限制为预定数量的整数

c++ - 允许碰撞的极快哈希函数

c - 'return type' 为标签的函数有什么作用?

jquery - 更改日期格式验证、mvc 3 和 jQuery

javascript - 用于选择 JavaScript 函数的 html 文本

c++ - volatile sig_atomic_t 的内存安全

javascript - 如何在 Bootstrap datetimepicker 中限制最小-最大时间

从 C 中的标准输入检查文件中的格式和字符?

javascript - 是否可以自动将 div 的内容复制为输入值