在这个switch
和while
的组合中,当我按'a'或'b'时,它很好,但我不希望程序在用户输入'ab'时打印1
和2
。
当用户输入多个字符时,如何打印错误消息?
#include <stdio.h>
int main() {
char move;
while (move != 'd') {
printf("enter a move : ");
scanf(" %c", &move);
switch (move) {
case 'a':
printf("1\n");
break;
case 'b':
printf("2\n");
break;
case 'c':
printf("3 \n");
} // switch
} // while
}
样本输出:
enter a move : a
1
enter a move : b
2
enter a move : ab
1
enter a move : 2
当我输入'ab'、'ac'或'bc'或类似的值时,程序应打印错误消息。
1条答案
按热度按时间fnx2tebb1#
我建议使用
fgets
来解析输入。避免常见的边缘情况会变得有些棘手,你需要处理换行符,当你按Enter键时,它也会从你的输入中解析出来,你需要清除输入以准备下一个循环,因为fgets
也解析\n
,你需要避免在某些情况下处理它,这里仅举几个常见的例子。你可以这样做:
你可以在这里试试:https://onlinegdb.com/S6Uh3mrHX
但是,如果您必须使用
scanf
,这里有一个可能的解决方案:你可以在这里试试:https://onlinegdb.com/Hcu8dlb04G
您可能还需要处理其他边缘情况,例如,假设用户输入
j
,没有输入错误,它只是跳到下一个输入循环(您可以在switch
中处理此问题),您可能还希望添加对大写字母的支持。1 - UB:未定义的行为,定义:https://port70.net/%7Ensz/c/c11/n1570.html#3.4.3