![](/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.