首页 > 解决方案 > 在抛出“int”实例后调用终止

问题描述

当我尝试输入糟糕的名字(非数字或字母数字)时,我想抛出异常。第一次它运行良好,但是当我从 catch 调用再次进入功能并再次输入坏名时,我收到此错误:在抛出'int'实例后调用终止"

int main(int argc, char *argv[]) {
    int numberOfWarrior = atoi(argv[1]);
    int numberOfthief = atoi(argv[2]);
    int numberOfnecromancer = atoi(argv[3]);
    int vecorSize = numberOfnecromancer + numberOfthief + numberOfWarrior;
    vector<Hero*> turnOfPlayer;
    //Enter Warrion Players
    if(numberOfWarrior>0) {
        try {
            enterWarrior(0, turnOfPlayer, numberOfWarrior,"warrior");
            }
        catch (int i) {
            cout << "Invalid name of user. You can only choose letters or numbers. Try again please." << endl;
            enterWarrior(i, turnOfPlayer, numberOfWarrior, "warrior");  // my program terminate when i enter to function from here
        }
    }

void enterWarrior(int index, vector<Hero*> v,int numOfWarrior, std::string Type)
{
    std::string nameOfwarrior;
    for(int i=index; i<numOfWarrior; i++)
    {
        cout << "Please insert " << Type << " number " << i+1 << " name:";
        cin >> nameOfwarrior;
        if(!digitCheck(nameOfwarrior))
            throw i;  // in the second time i get the error here 
        if(Type.compare("warrior")==0) {
            Warrior *warr = new Warrior(nameOfwarrior);
            v.push_back(warr);
        }
        if(Type.compare("thief")==0) {
            Thief *thief = new Thief(nameOfwarrior);
            v.push_back(thief);
        }
        if(Type.compare("necromancer")==0) {
            Necromancer *nec = new Necromancer(nameOfwarrior);
            v.push_back(nec);
        }
    }
}

我不知道我该如何解决谢谢

标签: c++clion

解决方案


正如评论中所说,只需使用循环,例如:

if(numberOfWarrior>0) {
  int firstIndex = 0.

  for (;;) {
    try {
      enterWarrior(firstIndex, turnOfPlayer, numberOfWarrior,"warrior");
      // if we are here that means all is ok, go out of the loop
      break;
    }
    catch (int i) {
      cout << "Invalid name of user. You can only choose letters or numbers. Try again please." << endl;
      firstIndex = i;
    }
  }
}

向量中的警告 void enterWarrior(int index, vector<Hero*> v,int numOfWarrior, std::string Type)是按值给出的,所以enterWarrior修改了向量的一个副本,所以通过 void enterWarrior(int index, vector & v,int numOfWarrior, std::string Type)`

Type.compare("warrior")==0etc 不是很容易阅读,你可以用(Type == "warrior")etc 替换它们,我们是 c++ 而不是 Java

当前一个“如果”为真时,一些“如果”可以是“其他如果”,不进行比较。如果Type不是预期的,则最终的else似乎也丢失了,以表明问题无论如何


推荐阅读