2011-03-26 89 views
0

使用此代码时,它会抛出一个未处理的写入异常,我几乎可以肯定是使用atoi()函数。C++ - 使用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; 
        } 
} 

回答

6

用途:

char item[20]; 

char * item = "",使项目点只读存储器 - 你试图修改它。指向字符串的指针最好编写为const char * item = "" - 然后编译器将确保您不修改它。 char * item = ""合法的原因是与C向后兼容。

+0

我知道有一个数组在其中。>。谢谢 – pighead10 2011-03-26 15:19:27

+3

更好的是,使用'std :: string'。 – 2011-03-26 15:20:48

+0

现在如果我输入'back',它会输出'Command not recognized'命令? – pighead10 2011-03-26 15:24:48

相关问题