【发布时间】:2015-12-15 20:58:58
【问题描述】:
我正在使用 do-while 循环将菜单打印到屏幕上。我正在阅读选择作为一个整数。问题是,如果用户输入一个字符,程序就会爆炸。我怎样才能避免这种情况?
#include <stdio.h>
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
scanf("%d", &choice);
return choice;
}
int main() {
int choice;
do {
choice = menu();
if (choice != 4) {
if (choice == 1)
//lab5(choice);
else if (choice == 2)
//lab10(choice);
else if (choice == 3)
// lab11(choice);
else
printf("invalid choice\n");
}
} while (choice != 4);
return 0;
}
【问题讨论】:
-
为避免这种情况,请读入一个字符串,然后自行将其转换为整数。
-
检查来自
scanf的返回以确保它是好的。如果没有清除缓冲区,请重试。 -
main()函数作为一个简单的switch()语句会更清晰 -
这里有点幽默:从程序中删除爆炸物质和爆破帽,然后用户不能'炸毁'