抛出"int"实例后调用的终止

terminate called after throwing an instance of 'int'

本文关键字:终止 调用 实例 int 抛出      更新时间:2023-10-16

当我尝试输入糟糕的名称(非数字或字母数字)时,我想抛出 exption。 第一次它运行良好,但是当我从 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);
        }
    }
}

我不知道如何解决它谢谢

正如在

评论中所说的那样,只需使用循环,例如:

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")==0等不是很容易阅读,你可以用(Type == "warrior")等替换它们,我们是用 C++ 而不是 Java

一些"如果"可以是"else if",当前面的"如果"为真时,不会一无所获。如果类型不是预期的,则似乎也缺少最后一个其他内容,以指示问题

相关文章: