c - while 循环内的 switch 语句。我如何重复用户的选择?

标签 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);
  }
}

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

最佳答案

这里有两个问题。

其中一个是:

您没有在大小写之间使用break语句。在您的情况下,无需在每种情况后放置 scanf 语句,只需将 switch 中的所有 scanf 替换为 break 即可。如果有超过 1 种情况,则必须使用中断。因为 switch 不能替代 if ... else 语句。

第二个是:

它会进入无限循环,因为如果匹配失败,scanf() 将不会消耗输入 token 。 scanf() 将尝试一次又一次地匹配相同的输入。你需要刷新标准输入。 (刷新输入流会调用未定义的行为。这是严格禁止的行为。)。

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

否则试试这个

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

关于c - while 循环内的 switch 语句。我如何重复用户的选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986907/

相关文章:

java - 带有内部赋值的 While 循环导致检查样式错误

python - 在 Python 中切换

javascript - 如果我的任何 switch case 匹配,我如何运行附加功能?

java - 我的 java 循环出现问题

c - 作业 3.exe : 0xC0000005: Access violation reading location 0x33772c58 中 0x77ea15de 处出现未处理的异常

c# - 当任何 TextBox 的文本发生变化时触发事件处理程序

python - ctypes 上的 PyObject_Str 段错误通过了字典

c - 当来自另一个线程的消息时,Winapi 控件不适本地访问内存

java - 数组大小不确定的写入循环

java - 如何从 while 循环内的 if 条件中断 while 循环?