这可能是一个简单的答案。我只用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;
}
,为什么你有吗? ---'scanf(“%d%c”,&menuSelection,&enter);'...为什么不只是'scanf(“%d”,&menuSelection);'? – sukhvir
使用fgets代替'char buffer [128]; fgets(buffer,128,stdin); menuSelection = atoi(buffer);' –
@sukhvir这是一个破解,因为'scanf()'不会读取换行符,否则它将在下一次迭代时失败。但我必须承认这太可怕了。改用'fgets()'和'strtol()'。 – 2013-10-07 05:38:02