在这个开关和 while 组合中。当我按“a”或“b”时很好,但我不希望程序在用户输入“ab”时打印 1 和 2。当用户输入多个字符时如何打印错误消息?。当我输入“ab”、“ac”或“bc”时程序应该打印错误信息。
#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
我敢说,在 99.9% 的情况下,最好使用像
fgets
这样的东西来解析输入,它也是 crpss-platform,而且更健壮。
现在,如果你想避免常见的边缘情况,它会变得有点棘手,你需要处理换行符,当你按下回车键时,它也会从你的输入中解析出来,你需要为下一个循环清除输入,因为
fgets
也解析 \n
在某些情况下你可能想避免处理它,所以覆盖所有基础有点困难。
我会这样做:
您可以在这里尝试:https://onlinegdb.com/dwX9_Nm2F_
#include <stdio.h>
#include <string.h>
int main() {
char move[20] = {};
while (move[0] != 'd') {
printf("enter a move : ");
// parse and check fgets return to validate input
if (fgets(move, sizeof move, stdin) != NULL) {
// if we have more than 2 chars, error, fgets also parses \n and strlen counts it
if (strlen(move) > 2) {
printf("Error, invalid input\n");
// if the \n character wasn't already parsed we need to handle it
if (!strchr(move, '\n')) {
int c;
// this just clears the stdin input buffer
while ((c = getchar()) != '\n' && c != EOF) {}
}
// Since we got an error, let's reset our target buffer
move[0] = 0;
}
}
switch (move[0]) {
case 'a':
printf("1\n");
break;
case 'b':
printf("2\n");
break;
case 'c':
printf("3 \n");
} // switch
} // while
}