2013-02-14 65 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'它已被分配一個值。你也應該使用==來進行比較。你可以使用!運算符來否定條件。

相關問題