这可能是一个简单的答案。我只用 C 语言编程了一个月。我正在创建一个 C 程序,向用户显示菜单 1-4。菜单选项 1-3 要求用户输入整数,当输入整数时,程序会写入或“绘制”该数量的“点”或句点。第一个选项中的每一个都将执行相同的功能,但分别执行一个 while 循环、do-while 循环和一个 for 循环。终止程序的唯一方法是在主菜单中选择 4。
我的问题是如何让我的程序循环并继续正常工作。当我执行程序时,它第一次正常工作,但是当程序循环回到主菜单时。没有其他选项有效。IE:如果我再次尝试为“点图”输入一个整数,它就不能正常工作。
我也无法验证字母或“非数字”菜单上的输入,目前,如果您输入字母,它会破坏程序。
我不知道该做什么以及该去哪里。我不需要重写代码,也许只是一些关于在哪里使用它的想法。我会接受提供的任何参考资料或链接。我的不完整程序的副本包括在下面:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
system("cls");
int programRun=0;
int menuSelection=0;
int absmenuSelection=0;
int dotNumber=0;
int countNumber=0;
char enter;
while(programRun==0)
{
system("cls");
printf("\nplease make a number selection\n");
printf("Please select a choice:\n");
printf("[1] While loop...\n");
printf("[2] Do-While loop...\n");
printf("[3] For loop...\n");
printf("[4] Exit program...\n\n");
scanf("%d%c",&menuSelection,&enter);
absmenuSelection= abs(menuSelection);
if (absmenuSelection <1 || absmenuSelection>4)
{
}
switch (absmenuSelection)
{
case 1:
printf("\nPlease input a number for the amount of dots you wish to see...");
scanf("%d", &dotNumber);
if(dotNumber > 0)
{
while(countNumber<dotNumber)
{
countNumber++;
printf(".");
}
}
else{
printf("\nsorry, that is an invalid response. Now you have to try again.\n");
}
printf("\n");
system("pause");
break;
case 2:
printf("\nPlease input a number for the amount of dots you wish to see...");
scanf("%d", &dotNumber);
if(dotNumber > 0)
{
do
{
countNumber++;
printf(".",countNumber);
}
while( countNumber<dotNumber );
}
else
{
printf("\nsorry, that is an invalid response. Now you have to try again.\n");
}
printf("\n");
system("pause");
break;
case 3:
printf("\nPlease input a number for the amount of dots you wish to see...");
scanf("%d", &dotNumber);
if(dotNumber > 0)
{
for(countNumber=0;countNumber<dotNumber;countNumber++)
{
printf(".",countNumber + 1);
}
}
else
{
printf("\nsorry, that is an invalid response. Now you have to try again.\n");
}
printf("\n");
system("pause");
break;
case 4:
while(programRun>1)
programRun=1;
printf("\nOkay have a nice day");
return 0;
default:
printf("\nsorry that is an invalid statement, try again\n\n");
system("pause");
}}
system ("pause") ;
return 0;
}