用户只有“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/