【发布时间】: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 是的,你是对的。我检查了
option和ON_status的内存地址。两者都分配在相邻的内存地址中。 Null char 确实覆盖了ON_status变量
标签: c while-loop switch-statement boolean