2012-10-13 34 views
1

每當我鍵入命令在我的程序運行這個功能,它運行,然後崩潰說:爲什麼我的程序在運行這個特殊功能後崩潰?

「應用程序已請求運行時終止它以不同尋常的方式。」

它爲什麼這樣做?

void showInventory(player& obj) { 
    std::cout << "\nINVENTORY:\n"; 
    for(int i = 0; i < 20; i++) { 
     std::cout << obj.getItem(i); 
     i++; 
     std::cout << "\t\t\t" << obj.getItem(i) << "\n"; 
    } 
} 

std::string getItem(int i) { 
     return inventory[i]; 
    } 
+0

getItem()是如何寫的?它是否直接索引數組?你跑出界限了嗎? –

+2

這可能與'i'在每次循環迭代中增加3次這一事實有關。 – chris

+0

您正在添加一個字符串('char *')和'obj.getItem(i)'的返回值。你可能打算使用'<<'而不是'+'。 – Schnouki

回答

1

在此代碼:

std::string toDo(player& obj) //BY KEATON 
{ 
    std::string commands[5] = // This is the valid list of commands. 
    {"help", "inv"}; 

    std::string ans; 
    std::cout << "\nWhat do you wish to do?\n>> "; 
    std::cin >> ans; 

    if(ans == commands[0]) { 
     helpMenu(); 
     return NULL; 
    } 
    else if(ans == commands[1]) { 
     showInventory(obj); 
     return NULL; 
    } 
} 

需要是:

std::string toDo(player& obj) //BY KEATON 
{ 
    std::string commands[5] = // This is the valid list of commands. 
    {"help", "inv"}; 

    std::string ans; 
    std::cout << "\nWhat do you wish to do?\n>> "; 
    std::cin >> ans; 

    if(ans == commands[0]) { 
     helpMenu(); 
     return ""; 
    } 
    else if(ans == commands[1]) { 
     showInventory(obj); 
     return "";   // Needs to be '""' 
    } 
} 

感謝原型斯塔克!

0

在i = 19,你之後我成爲20數組中的最後一個項目,有另一個的getItem這應該引起越界異常

+1

如果你經歷過但沒有發生。 for循環將被調用'i = 18',然後在循環結束時爲20。所以當我在'for'中評估時'i'沒有達到19。我有同樣的想法... – tpg2114

+0

我看到你現在說的,修復它,但它仍然崩潰? – Tux

+0

我錯了。閱讀tpg2114的評論。 – Prabhu

0
for(int i = 0; i < 20; i++) { 
    std::cout << obj.getItem(i); 

這也不是很正確的。不要使用幻數。而不是20使用int LISTSIZE = obj.ListSize()(將由你來實現)

listSize = obj.ListSize(); 
    for(int i = 0; i <listSize ; i++) { 
     std::cout << obj.getItem(i); 

這樣,你一定會認爲你是不是超出範圍。

此外,如果你想打印在一個循環中2項(我不爲什麼得到的原因)你CAND做:

void showInventory(player& obj) { // By Johnny :D 
    std::cout << "\nINVENTORY:\n"; 
    int listSize = obj.ListSize()/2; //if you are sure that is odd number 
    for(int i = 0; i < listSize; ++i) { 
     std::cout << obj.getItem(i); 
     i++; 
     std::cout << "\t\t\t" + obj.getItem(i) + "\n"; 
    } 
} 
+0

ListSize是我可以使用的C++函數嗎? – Tux

+0

你應該寫一個類似於Prototype Stark寫的方法。 –

0

寫一個函數:

class player{ 
public: 
//--whatever it defines 
int ListSize() 
{ 
    return (sizeof(inventory)/sizeof(inventory[0])); 
} 
}; 

然後用

void showInventory(player& obj) { // By Johnny :D 
    int length = obj.ListSize(); 
    std::cout << "\nINVENTORY:\n"; 
    for(int i = 0; i < length; i++) { 
     std::cout << obj.getItem(i); 
     i++; 
     std::cout << "\t\t\t" << obj.getItem(i) << "\n"; 
    } 
} 
+0

不要使用i

+0

感謝讓我糾正它:-) –

+0

已將此代碼更改爲此。仍然崩潰... – Tux