2013-05-10 110 views
0

我使用的是whileswitchcase我的菜单声明,当它运行它口口声声说输入的选择,我知道while(1)创建一个无限循环,但有没有办法避免这种情况?虽然,开关,case语句

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; 
      } 

     } 
} 

任何帮助,将不胜感激。

+1

当你预计你的while循环退出? – johnchen902 2013-05-10 03:41:32

+2

你可以在需要的时候断开环路。 – 2013-05-10 03:46:18

+0

目前还不清楚你想要发生什么。如果你只想看一次,为什么要使用循环? – xaxxon 2013-05-10 07:07:24

回答

2

虽然(1)没问题。但是你必须有一些条件来完成循环。像:

while(1){ 
......... 
if(i == 0) 
    break; 
............ 
} 

在每一个 “%d” 和 “%C” 的开头添加一个空间,因为scanf函数总是让在缓冲区中的换行符:

"%d"->" %d" 
"%c"->" %c" 
+0

我有这些条件,情况1-5,但我试图使用循环的原因是因为它是一个双向链表,它需要不断添加到列表中。 – Hamas4 2013-05-10 15:45:39

+0

需要更多细节。 – Gisway 2013-05-10 16:08:18

+0

查看上面完整代码的菜单。我想说的是我明白,虽然(1)创建了一个无限循环,但这不是问题,我可以在while(i!= 4)时停止它,但它一直说输入选择。例如,如果我运行它并按1,我会在Enter开头选择Enter,但它不允许我输入任何内容,但如果按1并在下一个循环中添加'a',有用。 – Hamas4 2013-05-10 16:15:25

1

另外,你可能想在与输入有关的循环中加入一个条件,例如

do 
{ 
    printf("\n\nEnter Choice "); 
    scanf("%d",&i); 
    // the rest of the switch is after this 
} while (i != SOME_VALUE); 

请注意do循环的用法,它在一个值被读入i之后在最后测试条件。

1

替代解决方案,

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是任何整数通知停止循环。

+1

请记住,在switch中'break'会终止'switch'而不是封闭的'loop'。 – 2013-05-10 05:35:38

+0

@JonathanLeffler ..切换后再次检查while检查while循环的条件,这将成为false,因为== == SOME_VALUE – 2013-05-10 05:37:33

+0

好的 - 我没有注意到,你已经改变了循环while(1)',这是粗心的我的。 – 2013-05-10 05:45:18

1

我可能会写一个可以在循环中调用的函数:

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; 
} 

您还可以找到相关的讨论: