切换语句不响应Cin输入

时间:2017-10-16 14:10:00

标签: c++

这是我的第一篇文章。我是一名业余程序员,刚刚学习了类和继承。所以我以为我会通过尝试制作基于文本的RPG来练习我学到的东西。但是,我在此函数中遇到了Switch语句的问题:

...
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,它仍会打印“Warrior(HP .....”。  任何帮助都会得到赞赏。

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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

答案 2 :(得分:0)

switch的行为类似于可转位gotocase - s只是“标签”,当“点击”下一个case时,代码只会落空。如果要结束某个开关案例,则必须使用break终止它。像这样:

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