当我尝试输入不良名称(非数字或字母数字)时,我想抛出例外。第一次运行良好,但是当我从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);
}
}
}
我不知道该如何解决 谢谢
答案 0 :(得分:0)
如前所述,只是使用循环,例如:
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
当上一个“ if”为真时,某些“ if”可以为“ else if”,不进行任何比较。如果不是 Type 的类型,最终的 else 似乎也丢失了,无论如何提示问题