因此,assignemt将打印带有选项的菜单,如果用户输入无效选项(不是1,2,3,4,5,6),则会输出错误并要求用户再次选择。 如果用户总输入错误输入5次,程序将退出。
int main() {
printf("Welcome, please choose one of the options below: \n ");
printf( "1.Exit \n ");
printf( "2.Print menu again \n ");
printf( "3. ");
printf( "4.. ");
printf( "5. ");
printf( "6. ");
printf("Enter your choice: ");
scanf("%d" , &choice);
if( (choice > 6) || (choice < 1) ) {
do {
count++;
printf(" Wrong input, please try again (Enter 2 for re-printing the menu). \n " );
printf("Enter your choice: ");
scanf("%d", &choice);
if(choice==2){
do {
printf("Welcome, please choose one of the options below: \n "); //prints of the screen the following in a loop
printf("1.Exit \n ");
printf("2.Print menu again \n ");
printf("3. ");
printf("4. ");
printf("5. ");
printf("6.");
printf("Enter your choice: ");
scanf("%d", &choice);
} while (choice==2);
}
} while (count < 4) ;
printf("%s" , "You have made 5 menu errors.Bye Bye!!! \n ");
}
while(1) {
.
}
* while(1)代表整个代码,将整个代码放入重用
**我没有使用switch-case,因为它禁止使用它
现在,问题是,如果我先输入错误的输入,请举例说,&#39; 7&#39; (这不是菜单中的选项),它会打印&#34;输入错误,请再试一次&#34;。到现在为止还挺好。 但是,如果我按2重新打印菜单,然后按任意数字,即使它是一个有效的选择,它也会打印错误的输入&#34;。 另外,如果我按下&#39; 2&#39;要重新打印菜单,然后按1,则需要按两次1才能退出程序,而不是只按一次。
答案 0 :(得分:1)
以上答案看起来是正确的,但您可以使用以下代码作为其工作且易于理解的任何人!
#include <stdio.h>
void printMenu()
{
printf("Welcome, please choose one of the options below: \n ");
printf( "1.Exit \n ");
printf( "2.Print menu again \n ");
printf( "3. ");
printf( "4.. ");
printf( "5. ");
printf( "6. ");
}
int main()
{
int choiceValid=0, count=0, choice;
printMenu();
while(choiceValid==0 && count<=5)
{
printf("Enter your choice: ");
scanf("%d" , &choice);
if(choice==2)
{
printMenu();
continue;
}
if( choice<=6 && choice>=1 )
choiceValid=1;
else
{
count++;
printf("\nWrong input, please try again (Enter 2 for re-printing the menu). \n " );
}
}
return 0;
}
答案 1 :(得分:0)
将if((choice==2) || (choice > 6) || (choice < 1) )
替换为while (choice==2);
将if(2 == choice) count = 0;
else if (choice > 6) || (choice < 1) count ++;
替换为while(((choice == 2)||(choice&gt; 6)||(choice&lt; 1))&amp;&amp;(count&lt; 4))
将以下块放在同一个while循环中。
{{1}}