[英]Repeat a menu and prompt if the user entered invalid choice in C
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)
看一下以下更改:將您的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');
第一件事, break;
在每種情況下,僅適用您選擇的情況。 要解決2次打印問題,只需在scanf("%c", &choice);
更改%c scanf("%c", &choice);
到%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');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.