void menu(){
printf("\n");
printf("1. Convert integers in decimal number system to binary numbers \n");
printf("2. Compute a consecutive square root expression \n");
printf("3. Solve a quadratic equation \n");
printf("4. Print something fun \n");
printf("q. Quit\n \n");
printf(" Enter your choice: ");
}
main () {
char choice;
do {
menu();
scanf("%c", &choice);
switch (choice){
case '1':
...
case '2':
....
case '3':
...
case '4':
....
default:
printf("Wrong choice. Please enter again: ");
break;
}
}
while (choice != 'q');
}
这是我的一般想法,但我不能让它提示错误的选择并重复菜单。当我输入错误的选项时,输出如下: 例如,我输入了5:
Enter your choice: 5
Wrong choice, please enter again:
1. Convert integers in decimal number system to binary numbers
2. Compute a consecutive square root expression
3. Solve a quadratic equation
4. Print something fun
q. Quit
Enter your choice: (this is where I get to input)
答案 0 :(得分:1)
看看下面的变化: 将scanf()更改为
scanf(" %c",&choice);
%c之前的空格将确保忽略包括换行符在内的所有特殊字符。没有这个,每次缓冲区中都有换行符并且scanf从中读取,你会看到你的外观不起作用预期
在此之后,请确保一旦遇到默认情况,您需要从while()循环中断。
do {
menu();
scanf(" %c", &choice);
switch (choice){
case '1':
break;
case '2':
break;
case '3':
break;
case '4':
break;
default:
{
printf("Wrong choice. Please enter again: ");
break;
}
}
}
while (choice != 'q');
答案 1 :(得分:0)
首先,在每种情况下都放break;
,因此只有您选择的情况才会适用。要解决2次打印问题,只需将scanf("%c", &choice);
中的%c更改为%s>> scanf("%s", &choice);
这是代码:
#include <stdio.h>
void menu(){
printf("\n");
printf("1. Convert integers in decimal number system to binary numbers \n");
printf("2. Compute a consecutive square root expression \n");
printf("3. Solve a quadratic equation \n");
printf("4. Print something fun \n");
printf("q. Quit\n \n");
printf(" Enter your choice: ");
}
main () {
char choice;
do {
menu();
scanf("%s", &choice);
switch (choice){
case '1':
printf("1 \n");
break;
case '2':
printf("2 \n");
break;
case '3':
printf("3 \n");
break;
case '4':
printf("4 \n");
break;
case 'q':
break;
default:
printf("Wrong choice. Please enter again: ");
break;
}
}
while (choice != 'q');
}