【问题标题】:C++ - Unhandled exception when using atoi()C++ - 使用 atoi() 时未处理的异常
【发布时间】:2011-03-26 15:16:50
【问题描述】:

使用此代码时,它会引发未处理的写入异常,我几乎可以肯定这与 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;
                    }
}

【问题讨论】:

    标签: c++ exception atoi unhandled


    【解决方案1】:

    用途:

    char item[20];
    

    char * item = "" 使 item 指向只读内存 - 您正在尝试修改它。指向字符串文字的指针最好写成const char * item = "" - 然后编译器会确保你不会修改它。 char * item = "" 合法的原因是向后兼容 C。

    【讨论】:

    • 我知道其中有一个数组有关 >.> 谢谢
    • 更好的是,使用std::string
    • @Pig Head:使用 strcmp 而不是 == 来比较 C 字符串。或者只是按照每个人的建议,使用 std::string :)
    • 我将使用 strcmp - 我使用的是 std::string 但您无法使用 atoi() 将它们转换为整数。
    • @猪头:当然可以,atoi(str.c_str())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多