C++ - 使用atoi时的未处理异常()

pig*_*d10 0 c++ unhandled exception 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;
                    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 6

使用:

char item[20];
Run Code Online (Sandbox Code Playgroud)

char * item = ""使项目指向只读内存 - 您正在尝试修改它.字符串文字的指针更好地编写为const char * item = ""- 然后编译器将确保您不修改它.char * item = ""合法的原因是向后兼容C.

  • 更好的是,使用`std :: string`. (3认同)
  • @Pig Head:当然可以,atoi(str.c_str()) (2认同)