Question

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;
                    }
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top