[英]How to keep a while loop going?
I am working on a program that is supposed to keep asking the user for input, sort of like a menu until they choose the option to quit.我正在开发一个程序,它应该不断要求用户输入,有点像菜单,直到他们选择退出选项。 Depending on what they choose, some sort of operation will be done depending on the choice.
根据他们的选择,将根据选择进行某种操作。 Right now I am just trying to test that the menu will keep being printed to the user, but it exits automatically once i run the program once.
现在我只是想测试菜单是否会继续打印给用户,但是一旦我运行程序一次它就会自动退出。 This is what I have:
这就是我所拥有的:
#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 is the option that would quit the program immediately if selected, but the other ones are not. Q 是选择后会立即退出程序的选项,但其他选项则不然。
An example output I have gotten:我得到的一个示例输出:
Choose an Option (C, M, Q, S, V): M
M working. (base)
The break exits from the while loop. break 退出 while 循环。 The
if
statement is not a looping structure so the break
is for the nearest loop which is the while. if
语句不是循环结构,所以break
是针对最近的循环,即 while。
if you want the menu to keep printing to the user just remove the break statement in each of the (if,else if) blocks.如果您希望菜单继续向用户打印,只需删除每个 (if,else if) 块中的 break 语句。 because the break and continue statements affects the nearest repetition statement to them which is the while loop in your code.
因为break和continue语句会影响与它们最近的重复语句,即代码中的while 循环。
You need to initialize str
.您需要初始化
str
。
int main()
{
char str = 0;
unsigned int hex = 0;
int decimal = 0;
...
it seems you want to break
on 'Q'
only :它似乎要
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.