C ++ - 使用ATOI()时未处理异常
题
使用此代码时,它会抛出未处理的写作异常,我几乎可以使用ATOI()函数。
while(true){
char* item = "";
cin >> item;
int numItem = atoi(item);
if(numItem){
if(numItem<=backpackSpaces){
equipItem(backpack[numItem]);
break;
}else{
cout << "No such item." << endl;
}
}else if(item == "back"){
cout << "Choose an option from the original choices. If you can't remember what they were, scroll up." << endl;
break;
}else{
cout << "Command not recognised." << endl;
}
}
. 解决方案
使用:
char item[20];
.
char * item = ""
使项目指向只读内存 - 您正在尝试修改它。指向字符串文字的指针更好地编写为const char * item = ""
- 然后编译器将确保不修改它。char * item = ""
的原因是与c的后向兼容性。
不隶属于 StackOverflow