c - 为什么这个 switch 语句在运行时会结束 while 循环?
问题描述
我希望这个程序从开关中断并返回到 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
和 option 在内存中被声明为 close by,所以它正在覆盖ON_status
。
要查看正在发生的事情,您可以打印ON_status
外部的值,switch
您会观察到它是 0。
为了解决这个问题,我想我会scanf
用
option = getc(stdin);
推荐阅读
- symfony - 带有注释的最小 symfony 设置
- python - 我想使用python将数据从txt文件提取到csv文件
- google-analytics - Google Data Studio 数据透视表 - 添加多个月份 (Google Analytics)
- autodesk-forge - 如何使用各种 Forge Viewer 转换
- microcontroller - ATTINY 85 睡眠模式
- python - 在 python 上创建登录页面
- c - C中系统命令的服务器延迟
- android - Fragment NavHostFragment 没有创建视图
- instagram - 在 Instagram 发布端点 api 中使用 id 而不是短代码
- templates - Orchard Core:如何从 Liquid tempale 中的 ContentItem 创建形状