c++ - 在抛出“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);
}
}
}
我不知道我该如何解决谢谢
解决方案
正如评论中所说,只需使用循环,例如:
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
etc 不是很容易阅读,你可以用(Type == "warrior")
etc 替换它们,我们是 c++ 而不是 Java
当前一个“如果”为真时,一些“如果”可以是“其他如果”,不进行比较。如果Type不是预期的,则最终的else似乎也丢失了,以表明问题无论如何
推荐阅读
- reactjs - 如何使用 reducer 正确处理反应状态和专业人士更新
- javascript - 写入 JSON(Discord.JS 的节点)
- python - 在我收到来自 django 的贝宝的获取请求后,我的会话正在自动清除
- swift - Firebase Swift 命名孩子 - 第 N 个名字/重复的孩子?
- cakephp - CakePHP 4 验证上传文件扩展名
- r - 打印 R 中元音最少的句子
- flutter - 哪个 ThemeData 属性会更改抽屉背景颜色?
- excel - 如果电子邮件中的字符串与电子表格中的字符串匹配,VBA脚本将类别添加到Outlook电子邮件?
- php - 使用php从mongodb中的数组获取文档
- assembly - ARMv7:有没有办法通过寄存器中的链接进行分支?