为什么这个 switch 语句在 运行 时结束 while 循环?

Why does this switch statement end the while loop when it's run?

我希望这个程序从 switch 中断并返回到 while 循环。为什么它不起作用?

我在 while 循环中放置了一个 switch 语句。我认为休息会干扰 while 循环,使其提前中断。我该如何解决这个问题?

#include <stdbool.h>
#include <stdio.h>


 int main(void)
 {
 
 bool ON_status = true;
 char option = '0';

  while (ON_status == true)
  {
      printf("enter option 1, 2, 3, or 4.\n");
      printf("Select an option from the menu above then press the enter key:  ");
      scanf("%1s", &option);

      switch (option)
      {
      case '1':
           printf("option1 was selcted");
           break;

      case '2':
           printf("option2 was selcted");
           break;

      case '3':
           printf("option3 was selcted");
           break;

      case '4':
           printf("option4 was selcted");
           ON_status = false;
           break;

      default:
           break;
      }
  }
 return 0;
}

您的代码的问题在于行

scanf("%1s", &option);

溢出 option 中的内存。

C 中的字符串以 null 结尾。所以 '%1s' 存储一个字符和一个空终止符。但是您的 option 变量只有一个字符长,那么零(或 NULL、NUL、null,具体取决于您的命名)去哪儿了?

在这种情况下,因为 ON_status 和选项在内存中附近声明,所以它正在覆盖 ON_status

要查看发生了什么,您可以在 switch 之外打印 ON_status 的值,您会发现它是 0。

要解决这个问题,我想我会用

替换你的 scanf
option = getc(stdin);