使用if语句查看用户是否输入了正确的字符串

时间:2016-08-22 17:44:43

标签: c++ if-statement

不确定如何确保用户在控制台中输入正确的字符串,然后将其与正确的if语句相关联。我也不确定如何为敏捷,力量和智力指定伤害值或护甲值,以便它们影响角色,而不仅仅是整数。

      class Character {
public:
    string name;
    string gender;
    string type;
    int strength;
    int agility;
    int intelligence;
    int level;
    int health;
    int experience;
    int mainweapon;
    int offhand;
    int chest;
    int legarmor;
    int gloves;
    int helmet;
    int gold;
    int faction;
};


int main()
{
    Character Charactername;
    Character Charactergender;
    Character Charactertype;
    Character Characteragility;
    Character Characterstrength;
    Character Characterintelligence;
    cout << "what is your name?\n";
    cin >> Charactername.name;
    cout << "Male or Female\n";
    cin >> Charactergender.gender;
    cout << "What class are you, Warrior, Mage or Rogue\n";
    cin >> Charactertype.type;
    cout << "Welcome to the Elysium " << Charactername.name;
    Sleep(5000);

    Character Characterhealth;
    Characterhealth.health = 100;
    if (Charactertype.type == "Warrior","warrior")
        Characteragility.agility = 6, Characterstrength.strength = 10, Characterintelligence.intelligence = 4;
    else if (Charactertype.type == "Mage","mage")
        Characteragility.agility = 4, Characterstrength.strength = 6, Characterintelligence.intelligence = 10;
    else if (Charactertype.type == "Rogue", "rogue")
        Characteragility.agility = 10, Characterstrength.strength = 4, Characterintelligence.intelligence = 6;
    else cout << "you have entered a invalid name" << main;
    cout << Characteragility.agility << endl << Characterstrength.strength << endl << Characterintelligence.intelligence;
    Sleep(2000);
};

1 个答案:

答案 0 :(得分:1)

首先

if (Charactertype.type == "Warrior","warrior")

不符合您的想法。 C ++使用&amp;&amp; for和and ||为或。所以,如果你想说的是类型是&#34; Warrior&#34;或者输入&#34; warrior&#34;,你应该做

if(Charactertype.type == "Warrior" || Charactertype.type == "warrior")
{
  //do something
}
else if( something something)
{
  //do something else
}

当您通过控制台输入字符串时,您可以执行相同的操作,如果输入不正确,您可以要求用户再次输入字符串。

你的代码也是一团糟。为什么不同的属性有不同的类对象?对象的整个要点是将整个数据存储在一个对象中,而不是为每个变量创建不同的对象。例如,当你谈论另一个玩家时,你只需要声明第二个Character对象。