C开关,如何修复多个默认打印?

问题描述 投票:0回答:2

如果我给我的程序这样: abcdefghijklmnopqrstuvwxyz 就这样回答了?! 无效命令a 无效命令c 无效命令 e 无效命令 g 无效命令我 无效命令 k 无效命令 m 无效命令 o 无效命令 q 无效命令 无效命令 u 无效命令 w 无效命令 y

知道为什么只有所有其他字母都会收到我的默认消息,以及为什么有这么多而不只是一个,我该如何解决这个问题,这样无论我输入多少个无效字符,我都只会收到一个默认消息?

这是我的代码的一部分:

while (1) {
scanf("%c", &command);
getchar();

switch (command) {
case 'A': // Adds a new entry to the program database.
if (scanf("%s %f", name, &price) != 2) {
printf("A should be followed by exactly 2 arguments.\n");
// while (getchar() != '\n'); // Clear the input buffer
} else {
getchar(); // Consume the newline character
addGame(&games, &numGames, name, price); // Pass pointer to games
}
break;
case 'B': // Buy game command, which sells a specified number of games
if (scanf("%s %d", name, &count) != 2 || count <= 0) {
getchar(); // Consume the newline character
printf("Number of bought items cannot be less than 1.\n");
} else {
getchar(); // Consume the newline character
buyGame(games, numGames, name, count);
}
break;
case 'L': //Prints a list of the program database into the standard output
printDatabase(games, numGames);
break;
case 'W': //Writes the program database into a text file
scanf("%s", filename);
getchar();
saveToFile(games, numGames, filename);
break;
case 'O': //Loads the database from the specified text file
scanf("%s", filename);
getchar();
loadFromFile(&games, &numGames, filename); // Pass pointer
break;
case 'Q': //Quits the program after releasing the program database
releaseMemory(games, numGames);
return 0;
case '\n': //Not sure i need this?
break;
default:
printf("Invalid command %c\n", command);
}
}

如果有人认为需要,我可以发送更多代码:)

c switch-statement default
2个回答
0
投票

您一次只能阅读一个字符,而不是整行。这就是为什么你会得到“这么多而不只是一个”。

要阅读整行,请使用

fgets
代替。如果需要,请添加仅输入一个字符的验证。

您每隔一个字符就被报告为错误的原因只是因为

getchar
之后的误导性
scanf("%c", &command)
调用。
scanf
调用将显示为,例如
a
,那么
getchar
调用将读取
b
。等等。


0
投票

在 while 循环的开始,你有

while (1) {
scanf("%c", &command);
getchar()
//...

所以当你输入这样的符号序列时

abcdefghijklmnopqrstuvwxyz

然后调用 scanf 读取一个字符,例如“a”,下一次调用 getchar 读取下一个字符“b”。由于命令“a”无效,因此下一次调用 scanf 会读取下一个字符“c”,调用 getchar 会读取字母“d”,依此类推。你所做的就是你得到的。

而不是这些电话

scanf("%c", &command);
getchar()

你可以像

一样使用
scanf

的一通电话
scanf(" %c", &command);

注意格式字符串中的前导空格。它允许跳过空白字符,包括换行符

'\n'
。如果输入无效,您应该清除输入缓冲区,例如

while ( getchar() != '\n' );
© www.soinside.com 2019 - 2024. All rights reserved.