开发者

C++ - Unhandled exception when using atoi()

When using this code, it throws an unhandled writing exception, which I'm almost certain is to do with the atoi() function.

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;
                    }
}


Use:

char item[20];

char * item = "" makes item point to read-only memory - you're trying to modify it. Pointers to string literals are better written as const char * item = "" - then the compiler will make sure you don't modify it. The reason char * item = "" is legal is backward compatibility with C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜