在while循环中切换语句。我该如何重复用户的选择?

时间:2016-12-06 02:35:17

标签: c while-loop switch-statement

我需要修改什么,以便在用户做出选择后,提示用户选择的原始语句(两个printfs)会不断重复?例如:

while(1) {
printf("What would you like to do next? \n");
printf("\tC to create more\n\tD to display\n\tI to insert at beginning\n\tN to exit\n");

scanf(" %c", &response);
switch(response) {
case 'C' : create(); scanf(" %c", &response);
case 'D' : display(); scanf(" %c", &response);
case 'I' : insert_at_beg(); scanf(" %c", &response);
case 'N': exit(0);
 default : printf("Invaild choice. Bye\n"); exit(0);
  }
}

我知道我的逻辑在某些地方到处都是。

1 个答案:

答案 0 :(得分:1)

这里有两个问题。

一个是:

你没有在案例之间使用break语句。在你的情况下,不需要在每个case之后放置scanf语句,只需用break替换switch中的所有scanf。如果有超过1个案例,则t必须使用break。因为switch不是if ... else语句的替代品。

第二是:

它进入无限循环,因为如果匹配失败,scanf()将不会使用输入令牌。 scanf()将尝试反复匹配相同的输入。你需要刷新标准输入。 (fflushing一个输入流会调用未定义的行为。严格来说不行。)。

if (!scanf(" %c", &response)) fflush(stdin);

否则试试这个

if (scanf(" %c", &response) == 0) { break; }