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];
    }   
4

4 回答 4

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

归功于原型斯塔克!

于 2012-10-13T23:14:44.990 回答
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";
    }
}
于 2012-10-13T21:35:52.803 回答
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 个项目(我不明白为什么),您可以这样做:

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";
    }
} 
于 2012-10-13T21:30:47.220 回答
0

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

于 2012-10-13T21:27:38.983 回答