c -在使用scanf组合时,如何避免多个输入



在这个switchwhile组合中,当我按'a'或'b'时很好,但我不希望程序在用户输入'ab'时打印12

如何在用户输入多于一个字符时打印错误信息?

#include <stdio.h>
int main() {
char move;
while (move != 'd') {
printf("enter a move :  ");
scanf(" %c", &move);
switch (move) {
case 'a':
printf("1n");
break;
case 'b':
printf("2n");
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'或类似的东西时,程序应该打印错误信息。

我建议使用fgets来解析输入。避免常见的边缘情况变得有些棘手,您需要处理换行符,当您按输入时,该换行符也将从您的输入中解析,您需要清除输入以准备下一个循环,因为fgets也解析n,您需要避免在某些情况下处理它,只是为了提到一些常见情况。

你可以这样做:

您可以在这里尝试:https://onlinegdb.com/S6Uh3mrHX

#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 inputn");
// 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("1n");
break;
case 'b':
printf("2n");
break;
case 'c':
printf("3 n");
}  // switch
}      // while
}

如果您必须使用scanf,那么这里有一个可能的解决方案:

您可以在这里尝试:https://onlinegdb.com/Hcu8dlb04G

#include <stdio.h>
int main() {
char move = 0;  // don't forget to initialize, accessing an unitialized
// variable is UB (1
while (move != 'd') {
printf("enter a move :  ");
if (scanf(" %c", &move) == 1) {
int c;
if (getchar() != 'n') {  // if more character were inputed other than newline
printf("Error, invalid inputn");                // print error
while ((c = getchar()) != 'n' && c != EOF) {}   // clear input buffer
move = 0;  // reset target variable
}
switch (move) {
case 'a':
printf("1n");
break;
case 'b':
printf("2n");
break;
case 'c':
printf("3 n");
}  // switch
}      // while
}
}

您可能仍然需要处理其他边缘情况,例如,假设用户输入j,没有输入错误发出,它只是跳转到下一个输入循环(您可以在switch中处理此问题),您可能还想添加对大写字母的支持。


1 - UB:未定义行为,定义:https://port70.net/%7Ensz/c/c11/n1570.html#3.4.3

最新更新