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

标签 c while-loop switch-statement boolean

我希望这个程序从 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 中的字符串以空字符结尾。所以 '%1s' 存储一个字符和一个空终止符。但是你的option变量只有一个字符长,那么零(或 NULL、NUL、null 取决于您的命名)在哪里?
在这种情况下,因为 ON_status和选项在内存中被声明在附近,它正在覆盖 ON_status .
要查看发生了什么,您可以打印 ON_status 的值。外switch你会观察到它是 0。
为了解决这个问题,我想我会替换你的 scanf
option = getc(stdin);

关于c - 为什么这个 switch 语句在运行时结束 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64832048/

相关文章:

c - 为什么 drand48() 和 friend 过时了?

服务器可以直接连接它所连接的两个套接字吗?

c - 表达式 "+ + a"是什么意思?

c++ - 概念同时执行循环

php变量改变结果

"default"条件语句的 Pythonic 方式?

c - 我的回调结构不起作用

c++ - 为什么while循环会导致指针出现问题?

c++ - 尝试制作一个 while 循环,减去一个数字直到达到所需值,如果减法超过所需值,则显示并停止

vb.net - VB.NET将Select Case语句堆叠在一起,例如在Switch C#/Java中