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

时间:2013-02-14 16:31:42

标签: c++ default

项目中的方向说明如下:

“对于活动级别,如果输入无效,请打印一条消息并告诉用户您假设他们是久坐不动的。”

以下是我当前的代码,我试图将其默认为"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语句将会成功,我想知道我现在设置它的方式是否会产生所需的结果。

2 个答案:

答案 0 :(得分:0)

在为分配值后,必须检查变量`activity_level'。您还应该使用==进行比较。你可以使用!操作员否定一个条件。

答案 1 :(得分:0)

如果您想默认为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,其他任何东西都需要双引号,因为它是一个字符串。