2012-10-26 114 views
0

我的程序應該顯示所需形狀的名稱。我不習慣使用字符串,所以如何回顯用戶輸入(C顯示錐等)?我在猜測某種if語句,但不知道如何寫它。用字符串迴應用戶輸入

樣品:

Hello. Welcome to the shape volume computing program. 
Which shape do you have? (C for cone, U for cube, Y, for cylinder P for pyramid, S for sphere, or Q to quit) 
Enter shape: U 
okay, cube. Please enter the length of a side: 3 
okay, the length of the side = 3 
the volume = 27 
enter shape: C 
okay, cone. Please enter the radius of the base: 2 
please enter the height: 3 
okay, the radius = 2 and the height = 3 
the volume = 12.56 
enter shape: Q 
bye! 

代碼:

int main() 
{ 
    string C,U,Y,P,S; 
    C= "cone"; 
    U= "cube"; 
    Y= "cylinder"; 
    P= "pyramid"; 
    S= "sphere"; 
    int Q= -1; 

    cout<< " Enter C for cone, U for cube, Y for cylinder, P for pyramid, S for sphere or Q 
    to quit. " <<endl; 
    cin>> C,U,Y,P,S,Q; 

    if(Q= -1) 
     cout<< " Goodbye! " <<endl; 
    return 0; 
} 
+0

我可以告訴你,現在,你的if語句分配Q可爲-1。 – M4rc

+0

是的,在這種情況下應該這樣做。 –

+0

閱讀至少前幾章C++的介紹將是一個好主意:http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – jogojapan

回答

1

聲明

cin>> C,U,Y,P,S,Q; 

意味着

(cin>> C),U,Y,P,S,Q; 

,因爲逗號運算符具有所有運算符的最低優先級。

所以它輸入一個字符時,進入C,然後(這是逗號操作做什麼)計算UYPSQ,與後者的作爲表達結果,然後將其丟棄的值。

這可能是而不是你認爲它做了什麼。

爲了使這項工作,你可以

  • 使用一個單一的輸入變量,也就是說,所謂的line

  • <string>頭使用getline函數來輸入一行。

  • 檢查是否該行輸入是"U",在這種情況下,做的東西或其他一些字母,在這種情況下做其他事情。 if聲明對此很有幫助。

+0

感謝您的提示! –

1

此錯誤代碼是錯誤的。

cin >> C,U,Y,P,S,Q; 

這會嘗試將任何用戶鍵入的內容寫入C指向的內存中。其他逗號分隔的部分是無效的個別語句。

你想要做的是將用戶的輸入寫入一個新的變量。

char choice; 
cin >> choice; 

然後看看是什麼,並相應地做出反應。

if ('C' == choice) 
{ 
    // print output 
} 
else if ('U' == choice) 
{ 
    // print output 

+0

正是我所需要的:) –