在C的while循环内切换语句 [英] Switch statement within while loop in C
问题描述
在while循环中有几篇关于switch语句的文章,除了它们都不是用C语言完成的事实,至少从我所见.我知道,C ++可以创建布尔表达式,但是在C语言中却不能.我有一个while循环,其中包含一个开关控件.但是,当我在交换机中编写break语句时,它可以返回到循环的开头,并使我的程序永远运行.忽略我使用的功能,因为它们肯定可以正常工作.我只需要澄清我对嵌套的处理.谢谢!
There are several postings concerning switch statements within while loops, except for the fact that none of them are done in C, at least from what I've seen. C++ can create boolean expressions, which I'm aware of, but not in C. I have a while loop that contains a switch control. However, when I write break statements within my switch, it goes back to the beginning of the loop and makes my program run forever. Ignore the functions I use, for they work for sure. I just need some clarification on my handling of the nesting. Thanks!
Here is my main.c:
while(1)
{
printf("0) Exit\n1) List Tasks\n2) Add Task\n");
printf("3)Delete Task\n4) Add Task From File\n");
printf("What would you like to do?\n");
fgets(buf1, 50, stdin);
p = atoi(buf1);
switch(p)
{
case 0:
break;
case 1:
printTaskList(pTaskList);
break;
case 2:
printf("Enter task name: ");
fgets(buf2,100,stdin);
printf("Enter task priority: ");
fgets(buf3,100,stdin);
printf("Enter task start date: ");
fgets(buf4,50,stdin);
pTask = makeTask(buf2,buf4,buf3);
addTaskToEnd(pTaskList,pTask);
break;
case 3:
printTaskList(pTaskList);
printf("What task would you like to delete? ");
fgets(buf6,50,stdin);
taskNum = atoi(buf6);
removeTask(pTaskList,taskNum);
break;
case 4:
printf("Enter the filename ");
fgets(buf7,50,stdin);
break;
default:
printf("ERROR: %d: Incorrect menu option\n", p);
}
}
推荐答案
break;
将退出最近的封闭的switch
或循环.要跳两个级别,您必须使用可怕的goto
或进行重组,以便return
可以完成所需的语义.
break;
will exit out of the nearest enclosing switch
or loop. To jump two levels, you'll have to use the dreaded goto
, or reorganize so a return
will accomplish the desired semantics.
while(1) {
switch(x) {
case 0: goto EndWhile;
}
}
EndWhile: ;
或
void loop() {
while(1) {
switch(x) {
case 0: return;
}
}
}
//...
loop();
//...
您可以在C语言中完全使用布尔表达式.只需使用int
.
You can totally use a Boolean expression in C. Just use an int
.
int quit = 0;
while(!quit) {
switch(x) {
case 0: quit = 1; break;
}
}
如果您确实想要C,它也具有布尔数据类型.
C also has a boolean data type, if you really want it.
#include <stdbool.h>
bool quit = false;
while(!quit) {
switch(x) {
case 0: quit = true; break;
}
}
还有一个选项,用于完全疯了.
#include <setjmp.h>
jmp_buf jbuf;
if (!setjmp(jbuf))
while(1) {
switch(x) {
case 0: longjmp(jbuf, 1);
}
}
这篇关于在C的while循环内切换语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!