The following code sets up an array of structures that is partially populated. one of the members is a pointer to a string (lunch[i].name). How do I populate the rest of the structure by user input? A 'for loop' causes a runtime error.
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
struct food
{
char *name;
int weight, calories;
};
const int MAXITEMS = 5;
void printList(food *lunch);
int main()
{
food lunch[MAXITEMS] = // see note 9.3
{
{"apple", 4, 100},
{"salad", 2, 80},
};
lunch[2].name = "onion";
lunch[2].weight = 1;
lunch[2].calories = 40; // This works: compiles and printList prints it.
printList(lunch);
return 0;
}
void printList(food *lunch)
{
cout << " Food Name Ounces Cal" << endl;
cout << " --------- ------ ---" << endl;
for(int j = 0; j < 3/*MAXITEMS*/; j++)
cout << setw(15) << lunch[j].name << " "
<< setw(6) << lunch[j].weight << " "
<< setw(5) << lunch[j].calories << endl;
return;
}