2013-02-14 102 views
0

该项目的方向规定如下:“对于活动水平,如果输入的是无效的,打印一条消息,告诉你是假设他们是久坐用户”如何在输入错误/无效输入时设置默认值?

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

+1

'activity_level ='SA''对'activity_level'做了*赋值*而不是比较。 'activity_level ==“SA”'是一个比较。 – 2013-02-14 16:35:15

+0

为什么在用户有机会输入之前检查activity_level? – 2013-02-14 16:37:11

+0

好点,我至少在发布之后看到了这个错误。 – user2072795 2013-02-14 16:38:29

回答

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,什么都需要用双引号,因为它是一个字符串。

+0

感谢您的帮助。欣赏它。 – user2072795 2013-02-14 16:51:31

0

您必须检查变量'activity_level'它已被分配一个值。你也应该使用==来进行比较。你可以使用!运算符来否定条件。

相关问题