[英]How to use a while loop in a switch case statement?(c++)
So when I put the limits of the integer that the switch case uses I keep getting a infinite number of the output of default for example:因此,当我设置 switch case 使用的整数的限制时,我不断获得无限数量的默认输出,例如:
int (num);
cout<<"Choose a number between 1-5"<<endl;
cin>>num;
while (num<1 || num>5)
{
switch (num)
{
case 1:
cout<<" Good"<<endl;
break;
case 2 :
cout<<" Okay"<<endl;
break;
case 3:
cout<<" Decent"<<endl;
break;
case 4:
cout<<" Nice Try"<<endl;
break;
case 5:
cout<<"Failed"<<endl;
break;
default
cout<<" Not Valid"<<endl;
break;
{
{
So for this example how would I make the user choose from 1-5 and if not repeat the loop in order for them to try again.所以对于这个例子,我将如何让用户从 1-5 中进行选择,如果不重复循环以便他们再次尝试。
This will loop until valid number is given then test it in the switch case.这将循环直到给出有效数字,然后在 switch 案例中测试它。
int num;
cout<<"Choose a number between 1-5"<<endl;
while(cin>>num && (num < 1 || num > 5));
switch (num)
{
... //for brevity
}
This will loop through the switch cases until a valid input is given.这将循环切换案例,直到给出有效输入。
int num;
bool keepLooping = true;
cout<<"Choose a number between 1-5"<<endl;
while(cin>>num && keepLooping)
{
keepLooping = false;
switch(num)
{
... //for brevity
default:
keepLooping = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.