为什么我的程序在运行这个特定的函数后会崩溃

Why does my program crash after running this particular function?

本文关键字:函数 崩溃 程序 我的 运行 为什么      更新时间:2023-10-16

每当我在程序中键入运行此函数的命令时,它就会运行,然后崩溃,说:

"应用程序已请求运行时以异常方式终止它。">

它为什么要这样做?

void showInventory(player& obj) {
std::cout << "nINVENTORY:n";
for(int i = 0; i < 20; i++) {
std::cout << obj.getItem(i);
i++;
std::cout << "ttt" << obj.getItem(i) << "n";
}
}
std::string getItem(int i) {
return inventory[i];
}   

在此代码中:

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 '""'
}
}

归功于原型斯塔克!

当i=19时,您得到数组中的最后一个项,在此之后i变为20,并且还有另一个getItem,它应该会导致越界异常

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

这不是很正确。不要使用幻数。使用int listSize=obj.listSize()(将由您实现)而不是20

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

通过这种方式,你将确保你没有超出范围。

此外,如果你想在一个循环中打印两个项目(我不知道为什么),你可以这样做:

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 << "ttt" + obj.getItem(i) + "n";
}
} 

编写一个函数:

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 << "ttt" << obj.getItem(i) << "n";
}
}