I came across a problem that made no sense to me but was solved by using parameters.
Basically, This worked:
void Inventory:: showInventory(char input)
{
//char input[80];
//cin >> input;
//char inventoryRequest[] = "i";
//int invent = strcmp (input,inventoryRequest);
//compare the player input to inventoryRequest (i) to see if they want to look at inventory.
if(input == 'i')
{
cout<< "\nYou have " << inventory.size() << " items.\n";
cout << "----------------Inventory----------------\n";
cout<< "\nYour items:\n";
for (int i= 0; i< inventory.size(); ++i)
cout<< inventory[i] << endl;
}
cout << "\n-----------------------------------------\n\n\n";
}
Rather than this:
void Inventory:: showInventory()
{
char input;
//char input[80];
//cin >> input;
//char inventoryRequest[] = "i";
//int invent = strcmp (input,inventoryRequest);
//compare the player input to inventoryRequest (i) to see if they want to look at inventory.
if(input == 'i')
{
cout<< "\nYou have " << inventory.size() << " items.\n";
cout << "----------------Inventory----------------\n";
cout<< "\nYour items:\n";
for (int i= 0; i< inventory.size(); ++i)
cout<< inventory[i] << endl;
}
cout << "\n-----------------------------------------\n\n\n";
}
Basically I thought this was the same. But obviously not when the first one worked and the second one didn’t.
Can anyone shed some light on this please.
In the first example,
inputis a parameter. It will be initialized by the callers with whatever value they choose to pass in.In the second example,
inputis an uninitialized variable. Reading it before it gets assigned (as you did) is undefined behavior, because it contains garbage at the time.