Reputation: 1916
Whenever I type the command to run this function in my program, it runs and then crashes saying:
"The application has requested the Runtime to terminate it in an unusal way."
Why does it do this?
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];
}
Upvotes: 1
Views: 1014
Reputation: 1916
In this code:
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;
}
}
Needs to be:
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 '""'
}
}
Credit to Prototype Stark!
Upvotes: 1
Reputation: 25705
write a function :
class player{
public:
//--whatever it defines
int ListSize()
{
return (sizeof(inventory)/sizeof(inventory[0]));
}
};
Then use
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";
}
}
Upvotes: 0
Reputation: 658
for(int i = 0; i < 20; i++) {
std::cout << obj.getItem(i);
This is not very correctly. Don't use magic numbers. Instead of 20 use int listSize = obj.ListSize() (which will be implemented by you)
listSize = obj.ListSize();
for(int i = 0; i <listSize ; i++) {
std::cout << obj.getItem(i);
In this way you will be sure that you are not out of range.
Also if you want to print 2 items in one loop (I don't get the reason why) you cand do :
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";
}
}
Upvotes: 0
Reputation: 3528
When i = 19, you get the last item in the array after which i becomes 20 and there is another getItem which should cause out of bounds exception
Upvotes: 0