2017-10-16 85 views
-4

這是我的第一篇文章。我是一位業餘程序員,他剛剛學習了類和繼承。所以我想我會嘗試製作基於文本的RPG來練習我所學到的知識。然而,有一個即時通訊問題,在這個功能我switch語句:Switch Statement不響應Cin輸入

... 
void Character::classSelect() 
{ 
    cout << "---- Choose the Class of your Hero ----\n"; 
    cout << "---- (1) -- Warrior -------------------\n"; 
    cout << "---- (2) -- Mage ----------------------\n"; 
    cout << "---- (3) -- Battlemage ----------------\n"; 
    cout << "---------------------------------------\n"; 
    int c; 
    cin >> c; 
    switch (c) 
    { 
    case 1: m_class = "Warrior", hp = 35, physDmg = 5, magicDmg = 1; 
    case 2: m_class = "Mage", hp = 20, physDmg = 1, magicDmg = 10; 
    case 3: m_class = "Battlemage", hp = 25, physDmg = 7, magicDmg = 7; 
    default: m_class = "Warrior", hp = 35, physDmg = 5, magicDmg = 1; 
     cout << "You chose : " << m_class << endl; 
    } 
} 
... 
    void Character::print() 
    { 
     cout << getCharClass() << " (HP:" << getHp() << "/DAMAGE-PHYICAL:" << 
      getPhysDmg() << "/DAMAGE-MAGICAL:" << getMagicDmg() << ")\n"; 
    } 
...   
     int main() 
     { 
      Character player; 
      player.classSelect(); 
      player.print(); 

      return 0; 
     } 

好像每次我輸入與「CIN」打印默認情況下,不管。例如,如果我輸入2仍然打印「勇士(HP .....」。 任何幫助將appereciated。

+4

您沒有開關 –

+2

的情況下,內寫任何break語句,我建議您[找到一個很好的初學者兩本書閱讀](http://stackoverflow.com/questions/388242/the -definitive-C-書指南和列表)。它應該解釋有關此問題的所有內容(以及更多可能遇到的問題!) –

+4

不要習慣濫用逗號運算符。用分號分隔您的語句,以最大限度地減少意外。 – molbdnilo

回答

0

你需要使用

break; 

的情況下指令來結束:你當前的代碼會去,直到循環結束,每次運行默認

switch (c) 
    { 
    case 1: m_class = "Warrior", hp = 35, physDmg = 5, magicDmg = 1; break; 
    case 2: m_class = "Mage", hp = 20, physDmg = 1, magicDmg = 10; break; 
    case 3: m_class = "Battlemage", hp = 25, physDmg = 7, magicDmg = 7; break; 
    default: m_class = "Warrior", hp = 35, physDmg = 5, magicDmg = 1; break; 
     cout << "You chose : " << m_class << endl; 
    } 

應該給你你想要的東西

reference

0

你應該在每種情況下添加一個休息......

switch (c) 
{ 
case 1: 
    m_class = "Warrior", hp = 35, physDmg = 5, magicDmg = 1; 
    break; 
case 2: 
    m_class = "Mage", hp = 20, physDmg = 1, magicDmg = 10; 
    break; 
case 3: 
    m_class = "Battlemage", hp = 25, physDmg = 7, magicDmg = 7; 
    break; 
default: m_class = "Warrior", hp = 35, physDmg = 5, magicDmg = 1; 
    cout << "You chose : " << m_class << endl; 
} 
0

switch表現得像可轉位gotocase -s只是「標籤」,當「點擊」下一個case時,代碼只會經歷。如果你想結束一個特定的開關情況,你必須用break來終止它。就像這樣:

switch (c) 
{ 
case 1: m_class = ...; break; 
case 2: m_class = ...; break; 
default: ...; 
}