I am writing up a code that involves inputting data from a file into an array of structs. The objective of this code is to create an array of structs for a list of menu items. The struct contains the string MenuItem for the menu items and the double MenuPrice of the item price. I'm having trouble with the data file because the given data file has a varying words for the menu item.
This is code I tried.
You need a delimiter such as '$', or ':' to mark the end of one input and the beginning of another. I would change the input file like this.
1 2 3 4 5 6 7 8
Plain Egg $1.45
Bacon and Egg $2.45
Muffin $0.99
French Toast $1.99
Fruit Basket $2.49
Cereal $0.69
Lemon Tea $0.75
Cheeseburger $2.25
Once you have the delimiter in place you can use getline to retrieve the data like this.
1 2 3 4 5 6 7 8 9 10 11
void getMenuFromFile(ifstream& inFile, menuItemType menu[], int menuSize)
{
for (menuSize=0; menuSize < NO_OF_MENU_ITEMS; menuSize++)
{
getline (inFile,menu[menuSize].MenuItem, '$'); //<------ gets a string up to the $ character and assigns to struct
inFile >> menu[menuSize].MenuPrice; // <---------------- gets the price after the $ character and assigns to struct
inFile.ignore(1000, '\n'); //<----------------------- Ignores any newlines
}
}
Wow, that's amazing. That function worked perfectly. I never knew getline can be used like that. Am I suppose to post my new code (it's basically the same thing with that new function added)?