【问题标题】:Input validation: checking multiple values输入验证:检查多个值
【发布时间】:2017-04-04 05:55:36
【问题描述】:

用户只有两个选择“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。你最终也抓住了换行符\n。因此,当您键入 a 时,c = getchar() != 'a' 的计算结果为 false 并跳过循环(我认为由于短路也跳过了第二个条件)。但是当你输入b、'b' != 'a''\n' != 'b'时,就进入了while循环。另外,我很确定这是以c = (getchar() != 'a') 执行的,这可能不是您所期望的。

标签: c validation input


【解决方案1】:

多个问题:

  • c = getchar() != 'a'不将读取的字符存储到c,它读取并丢弃字符并将比较结果存储到c

  • 您应该测试读取的字符的值,而不是读取第二个字符。

  • 您还应该检查 end if 文件,并使用 int 来允许 unsigned char 的所有值和特殊值 EOF

  • 倒带 stdin 以读取更多字节不会产生您期望的结果:要么成功,您将重新读取相同的字节,要么可能失败,stdin 未缓冲并绑定到设备。

试试这个:

#include <stdio.h>

int main(void) {
    int c;

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

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

【讨论】:

    【解决方案2】:

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

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

    否则,只要检查条件c = getchar() != 'b',c 将是\n

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 2014-03-16
      相关资源
      最近更新 更多