[英]While,switch, case statement
我在菜單上使用了while
, switch
, case
語句,當它運行時一直說輸入選擇,我知道while(1)
創建了一個無限循環,但是有辦法避免這種情況嗎?
while(1)
{
printf("\nEnter Choice \n");
scanf("%d",&i);
switch(i)
{
case 1:
{
printf("Enter value to add to beginning: ");
scanf("%c",&value);
begin(value);
display();
break;
}
case 2:
{
printf("Enter value to add last: ");
scanf("%c",&value);
end(value);
display();
break;
}
case 3:
{
printf("Value to enter before\n");
scanf("%c",&loc);
printf("Enter value to add before\n");
scanf("%c",&value);
before(value,loc);
display();
break;
}
case 4 :
{
display();
break;
}
}
}
任何幫助,將不勝感激。
While(1)正常。 但是您必須具備一些條件才能完成循環。 喜歡 :
while(1){
.........
if(i == 0)
break;
............
}
在每個“%d”和“%c”的開頭添加一個空格 ,因為scanf總是在緩沖區中保留換行符:
"%d"->" %d"
"%c"->" %c"
替代解決方案
int i = !SOME_VALUE;
while(i != SOME_VALUE)
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
switch(i)
{
case SOME_VALUE: break;
.
.
.
// the rest of the switch cases
}
}
SOME_VALUE
是通知停止循環的任何整數。
或者,您可能希望在與輸入有關的循環中放置一個條件,例如
do
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
// the rest of the switch is after this
} while (i != SOME_VALUE);
請注意使用do循環,該循環在將值讀入i后最后測試條件。
我可能會寫一個可以在循環中調用的函數:
while ((i = prompt_for("Enter choice")) != EOF)
{
switch (i)
{
case ...
}
}
而prompt_for()
函數可能是:
int prompt_for(const char *prompt)
{
int choice;
printf("%s: ", prompt);
if (scanf("%d", &choice) != 1)
return EOF;
// Other validation? Non-negative? Is zero allowed? Retries?
return choice;
}
您還可以在以下位置找到相關討論:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.