[英]While,switch, case statement
I'm using a while
, switch
, case
statement for my menu and when it runs it keeps saying enter choice, I know while(1)
creates an infinite loop but is there a way to avoid this? 我在菜单上使用了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;
}
}
}
Any help would be appreciated. 任何帮助,将不胜感激。
While(1) is ok. While(1)正常。 But you have to have some conditions to finish the loop. 但是您必须具备一些条件才能完成循环。 Like : 喜欢 :
while(1){
.........
if(i == 0)
break;
............
}
Add a space at the beginning of every "%d" and "%c",because scanf always leaves a newline characters in buffer: 在每个“%d”和“%c”的开头添加一个空格 ,因为scanf总是在缓冲区中保留换行符:
"%d"->" %d"
"%c"->" %c"
Alternative solution, 替代解决方案
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
is any integer number notify to stop loop. SOME_VALUE
是通知停止循环的任何整数。
Alternatively, you may want to put a condition in the loop that relates to the input, eg 或者,您可能希望在与输入有关的循环中放置一个条件,例如
do
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
// the rest of the switch is after this
} while (i != SOME_VALUE);
Note the use of the do loop, which tests the condition at the end, after a value has been read into i. 请注意使用do循环,该循环在将值读入i后最后测试条件。
I would probably write a function that can be called in the loop: 我可能会写一个可以在循环中调用的函数:
while ((i = prompt_for("Enter choice")) != EOF)
{
switch (i)
{
case ...
}
}
And the prompt_for()
function might be: 而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;
}
You can also find relevant discussion at: 您还可以在以下位置找到相关讨论:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.