我希望这个程序能够从 switch 语句中跳出,并回到 while 循环中。为什么它没有生效呢?
我在 while 循环中放置了一个 switch 语句。我认为这些 break 语句干扰了 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
会读取一个字符并添加一个空字符,而你没有足够的空间。这个空字符可能会覆盖你的布尔值,并使其变为false。 - Paul Ogilviewhile (ON_status == true)
最好改为while (ON_status)
。 - Keith Thompsonoption
和ON_status
的内存地址。它们都被分配在相邻的内存地址中。空字符确实覆盖了ON_status
变量。 - Krishna Kanth Yenumula