【发布时间】: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