输入错误/无效的输入时,如何设置默认值

How can I set a default value when incorrect/invalid input is entered?

本文关键字:输入 设置 默认值 何设置 错误 无效      更新时间:2023-10-16

项目中的方向说明如下:

"对于活动级别,如果输入无效,打印一条消息,告诉用户你假设他们久坐不动。"

以下是我当前的代码,我正在尝试将其默认为"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'被赋值后检查该变量。此外,您应该使用==进行比较。你可以使用!运算符来否定条件。