![](/img/trans.png)
[英]How to keep the while loop in a function when reading data with multiple conditions?
[英]How to keep a while loop going?
我正在开发一个程序,它应该不断要求用户输入,有点像菜单,直到他们选择退出选项。 根据他们的选择,将根据选择进行某种操作。 现在我只是想测试菜单是否会继续打印给用户,但是一旦我运行程序一次它就会自动退出。 这就是我所拥有的:
#include <stdio.h>
#include <string.h>
int main()
{
char str;
unsigned int hex;
int decimal;
while(str != 'Q'){
printf("Choose an Option (C, M, Q, S, V): ");
scanf("%c", &str);
if(str == 'C'){
printf("C working.");
break;
}
else if(str == 'M'){
printf("M working.");
break;
}
else if(str == 'S'){
printf("S working.");
break;
}
else if (str == 'V'){
printf("V working.");
break;
}
}
return 0;
}
Q 是选择后会立即退出程序的选项,但其他选项则不然。
我得到的一个示例输出:
Choose an Option (C, M, Q, S, V): M
M working. (base)
break 退出 while 循环。 if
语句不是循环结构,所以break
是针对最近的循环,即 while。
您需要初始化str
。
int main()
{
char str = 0;
unsigned int hex = 0;
int decimal = 0;
...
它似乎要break
对'Q'
只:
int main()
{
char str = null;
unsigned int hex;
int decimal;
while(1 == 1) { /* infinite loop until user breaks with a help of Q */
printf("Choose an Option (C, M, Q, S, V): ");
scanf("%c", &str);
if (str == 'Q') /* break on Q only */
break;
/* All the other cases: perform the operation and ask again */
if(str == 'C'){
printf("C working.");
}
else if(str == 'M'){
printf("M working.");
}
else if(str == 'S'){
printf("S working.");
}
else if (str == 'V'){
printf("V working.");
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.