开发者

C++ - Unhandled exception when using atoi()

开发者 https://www.devze.com 2023-02-19 18:25 出处:网络
When using this code, it throws an unhandled writing exception, which I\'m almost certain is to do with the atoi() function.

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

精彩评论

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