繁体   English   中英

切换时,案例说明

[英]While,switch, case statement

我在菜单上使用了whileswitchcase语句,当它运行时一直说输入选择,我知道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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM