我有一个while循环请求用户输入。在while while循环中我有一个switch语句。如何才能使其达到默认值,重复循环再次询问用户性别?
do
{
cout << "What is your weight?" << endl;
cin >> weight;
cout << "What is your height?" << endl;
cin >> height;
cout << "What is your age?" << endl;
cin >> age;
cout << "What is your gender?" << endl;
cin >> gender;
switch (gender)
{
case 'M':
case 'm':
cout << endl << Male(weight, height, age);
break;
case 'F':
case 'f':
cout << endl << Female(weight, height, age);
break;
default:
cout << "What is your gender?";
}
cout << "Do you want to continue? (Y/N)" << endl;
cin >> stopApp;
} while(toupper(stopApp) == 'Y');
答案 0 :(得分:5)
一个选项是设置一个布尔值,如果达到默认情况,则将其设置为true以重复。
bool repeat;
do {
repeat = false;
//switch statement
switch {
default:
repeat = true;
}
while(repeat);
你可以适当地使用重复来知道你想重复哪个问题。
答案 1 :(得分:4)
此类事情的典型模式是循环,直到用户输入有效输入。 IE
do {
cout << "What is your weight?" << endl;
cin >> weight;
cout << "What is your height?" << endl;
cin >> height;
cout << "What is your age?" << endl;
cin >> age;
cout << "What is your gender?" << endl;
cin >> gender;
} while (!validGender(gender));
// process valid input
虽然这并没有准确回答你的问题,但对于你想要做的事情来说,这是一个很好的模式。
答案 2 :(得分:1)
由于break
超载意味着“切换案例结束”和“退出循环”,这是goto
合适的异常时期之一。
do
{
again:
cout << "What is your weight?" << endl;
cin >> weight;
cout << "What is your height?" << endl;
cin >> height;
cout << "What is your age?" << endl;
cin >> age;
cout << "What is your gender?" << endl;
cin >> gender;
switch (gender)
{
case 'M':
case 'm':
cout << endl << Male(weight, height, age);
break;
case 'F':
case 'f':
cout << endl << Female(weight, height, age);
break;
default:
cout << "What is your gender?";
goto again;
}
cout << "Do you want to continue? (Y/N)" << endl;
cin >> stopApp;
} while(toupper(stopApp) == 'Y');
仅供参考“男性”和“女性”为not the only options for gender。根据你的更大目标,我建议你要么完全避免提出这个问题,允许用户提供任意的短语作为回应,或者,如果这是一个医疗应用,其中生物性是实际相关信息,请求相反(并再次允许提供任意短语,因为 不是二进制)。
答案 3 :(得分:1)
do
{
cout << "What is your weight?" << endl;
cin >> weight;
cout << "What is your height?" << endl;
cin >> height;
cout << "What is your age?" << endl;
cin >> age;
bool repeat(true);
do {
cout << "What is your gender?" << endl;
cin >> gender;
switch (gender)
{
case 'M':
case 'm':
cout << endl << Male(weight, height, age);
repeat = false;
break;
case 'F':
case 'f':
cout << endl << Female(weight, height, age);
repeat = false;
break;
default:
break;
}
} while(repeat)
cout << "Do you want to continue? (Y/N)" << endl;
cin >> stopApp;
} while(toupper(stopApp) == 'Y');