输入错误/无效的输入时,如何设置默认值
How can I set a default value when incorrect/invalid input is entered?
项目中的方向说明如下:
"对于活动级别,如果输入无效,打印一条消息,告诉用户你假设他们久坐不动。"
以下是我当前的代码,我正在尝试将其默认为"Sedentary"
,用户可以将其输入为SA或SA。无效输入的默认值应该使程序默认为久坐,我有点困惑我是否在正确的轨道上。
else if (gender == 'F' || gender == 'f') {
cout << "Please enter your Height in inches. (You may include a decimal) ";
cin >> height;
cout << "Please enter your Weight in pounds as a whole number. ";
cin >> weight;
cout << "Please enter your Age in years. ";
cin >> age;
cout << endl;
if (activity_level = 'SA' || activity_level = 'sa' || activity_level = 'LA' || activity_level = 'la' ||
activity_level = 'MA' || activity_level = 'ma' || activity_level = 'VA' || activity_level = 'va') {
cout << "Please enter your activity level." << endl << endl;
cout << "You may enter one of the following choices." << endl << endl;
cout << "Sedentary (Little or no exercise) "SA" or "sa" " << endl;
cout << "Lightly Active (Light exercise/sports 1-3 days a week) "LA" or "la" " << endl;
cout << "Moderately Active (Moderate exercise/sports 3-5 days a week) "MA" or "ma" " << endl;
cout << "Very Active (Hard exercise/sports 6-7 days a week) "VA" or "va" " << endl << endl;
cout << "Enter your activity level now. ";
cin >> activity_level;
cout << endl;
}
// Output for the message to defualt to Sedentary if you do not select activity level throught he proper input.
else {
activity_level =
cout << "I'm sorry I did not recogonize that activity level. We will assume a sedentary amount of exercise. "
}
}
基本上我在想,如果我在做什么;在else if
语句中使用另一个if语句会成功,我想知道目前设置它的方式是否会产生所需的结果。
如果你想默认为SA
,那么你可以这样做:
//Assume activity_level has had something assigned to it, to compare to.
if (activity_level == "SA" || activity_level == "sa" || activity_level == "LA" || activity_level == "la" ||
activity_level == "MA" || activity_level == "ma" || activity_level == "VA" || activity_level == "va")
{
//Do stuff if input is valid
}
// Output for the message to defualt to Sedentary if you do not select activity level throught he proper input.
else
{
activity_level = "SA";
std::cout << "I'm sorry I did not recogonize that activity level. We will assume a sedentary amount of exercise.";
}
同样,带有单引号的东西只能是一个char
,其他任何东西都需要在它周围加双引号,因为它是一个字符串。
必须在变量`activity_level'被赋值后检查该变量。此外,您应该使用==进行比较。你可以使用!运算符来否定条件。
相关文章:
- 为什么不能通过在错误输入后设置 std::cin.clear() 来使用 std::cin?
- 如何设置默认参数以防用户不输入另一个参数
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 如何使用Chrono或ctime libaray输入设置的开始和结束时间
- 如何在QT中为QInputDialog输入密码时设置背景非活动和灰色?
- 将函数更改为具有设置函数输入变量的方法的类
- 如何为用户设置仅输入 4 位代码的限制?
- GoogleMock:如何根据另一个输入参数设置ArgReferee?
- 无法在顶点着色器中设置输入的位置
- 将 TXT 文件设置为输出和和输入
- 如何初始化可以设置为默认数组并将输入/输出作为数组的类函数?
- 如何为输入设置变量编号和__android_log_print格式
- 如何在应用程序进行大量printf时,在固定输入的终端中设置最后一行
- 是否可以保证输入<Type>实数时复杂对象的虚部设置为零?
- 设置输入(CIN)的超时
- 设置Qlabel的输入蒙版
- 如何根据用户输入设置矢量的类型
- 如何对用户输入设置时间限制
- 如何仅对用户输入设置统一变量