2013-12-10 146 views
0

我想刷新一些簡單的C++程序,這一個有一些錯誤,我不明白爲什麼。我會寫的線以上的評論中的錯誤switch語句和其他erros

int main(void) 
{ 

bool x = true; 
char userInput; 
double weight; 
string planetName; 

while (x == true) 
{ 
             //endl; has the error "expected a ;" 
    cout << "Please enter your weight:" endl; 
    cin >> weight; 

    cout << "Please enter a planet name (The moon and pluto count)" endl; 
    cin >> planetName; 

    for (int i = 0; i < planetName[i] != '\0'; i++) 
    { 
     planetName[i] = tolower(planetName[i]); 
    } 

      //planetName has the error "expression must have integral or enum types" 
    switch (planetName) 
    { 
     //mercury has the error "too many characters in character constant" 
    case 'mercury' : 
     cout << "Your weight is :" << weight * .4155; 
    case 'venus' : 
     cout << "Your weight is :" << weight * .8975; 
    case 'earth' : 
     cout << "Your weight is :" << weight * 1; 
    case 'mars' : 
     cout << "Your weight is :" << weight * .3507; 
    case 'jupiter' : 
     cout << "Your weight is :" << weight * 2.5374; 
    case 'saturn' : 
     cout << "Your weight is :" << weight * 1.0677; 
    case 'uranus' : 
     cout << "Your weight is :" << weight * .8947; 
    case 'neptune' : 
     cout << "Your weight is :" << weight * 1.1794; 
    case 'pluto' : 
     cout << "Your weight is :" << weight * .0899; 
    case 'moon' : 
     cout << "Your weight is :" << weight * .116; 
    } 





    cout << "Try again?" << endl; 
    cout << "Press Y to see your weight on a different planet,or N to exit." << endl; 
    cin >> userInput; 
            // both == signs have "operand types are incompatable" 
    if (userInput == "y" || userInput == "Y") 
    { 
     break; 
    } 
    else if (userInput == "n" || userInput == "N") 
    { 
     x = false; 
    } 

} 




PressEnterToContinue(); 

return 0; 
} 

如果我做的事情在不到聰明的辦法,或者你認爲的更智能的方式做任何的這個,請隨時這樣說的。我真的不喜歡使用while循環,但有時候對於像這樣的短程序,我無法快速想到其他任何東西。

+1

爲什麼標記爲「C」? –

+1

change'to「。'只能包含一個字符 – SliceSort

+2

如果你想以更現代的C++方式來做到這一點,你可以使用'std :: map '來映射行星名稱與引力比 –

回答

1
        //endl; has the error "expected a ;" 
cout << "Please enter your weight:" endl; 

,因爲它說,你把一個endl它預期;。問題是缺少<<

 //planetName has the error "expression must have integral or enum types" 
switch (planetName) 

如上所述,switch必須具有整數或枚舉類型。改爲使用if

 //mercury has the error "too many characters in character constant" 
case 'mercury' : 

正如它所說的,字符常量必須是字符。使用"作爲字符串常量。

       // both == signs have "operand types are incompatable" 
if (userInput == "y" || userInput == "Y") 

由於userInput是一個字符,它不能等同於一個字符串。

+0

非常全面,儘管你忘了提及缺少的'break'語句 –

+0

我不認爲他提到了break語句,因爲我無法使用switch語句(我這樣做),感謝您的評論和回答! – trueCamelType

0

在C和C++中,switch語句僅針對整數類型(如int或shot或long或enum或char或它們的未簽名版本)進行定義。

字符串也應該用雙引號引起來。