這可能是一個簡單的答案。我只用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