【问题标题】:Why does this switch statement end the while loop when it's run?为什么这个 switch 语句在运行时会结束 while 循环?
【发布时间】:2021-02-26 02:50:53
【问题描述】:

我希望这个程序从 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;
}

【问题讨论】:

  • %1s 将读取一个字符并附加一个空字符,您没有空间。 (那个空字符可能会覆盖你的布尔值,它会变成假的。)
  • %1s 更改为%c
  • while (ON_status == true) 最好写成while (ON_status)
  • @john-kugelman 我不相信这是一个骗局。首先,它是 dup 的反转/反转......而且根本原因是缓冲区溢出。投票支持重新开放。
  • @PaulOgilvie 是的,你是对的。我检查了optionON_status的内存地址。两者都分配在相邻的内存地址中。 Null char 确实覆盖了 ON_status 变量

标签: c while-loop switch-statement boolean


【解决方案1】:

您的代码的问题在于该行

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

溢出option中的内存。

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

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

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

为了解决这个问题,我想我会将您的scanf 替换为

option = getc(stdin);

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2020-01-17
    • 2019-07-07
    • 2018-05-03
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多