Programming Assignment

[

You by now have lots of practice with built-in types such as float, int, etc. You also
have practice with incorporating these basic types into certain containers such as
vector.
Now comes time to create your own type.
struct is a means of building a more complicated type from simpler parts. struct was
introduced in C. In C++, structs were promoted to being nearly identical to the powerful
C++ feature class. In fact, everything you learn in this project about struct can be
applied (with next to no changes) to reimplimentation using class
Defining a struct
struct Person {
string fname;
string lname;
int age;
};
Then, the struct can be used like any type:
// Make one person.
Person p;
// Make a vector of persons.
vector<Person> people;
Accessing members of a struct
There is more than one syntax for accessing members of a struct. The basic form is
(assuming p as defined above):
cout << p.fname << " " << p.lname << " " << p.age << endl;
The Project
The Struct:
You will need to define your own struct. I called mine Food. Your struct must contain these
elements: the name of the food, the number of calories, the amount of sugar as a number, the
number of carbs, true or false of whether it is a drink, and a list of descriptions describing the
food such as Vegetarian.
The Data:
The data will be read in from a file. You will need to create your own data file that matches the
format described below.
Cool Ranch Doritos
150
1
18
False
Snack
Chips
Vegetarian
Coca-Cola
240
65
65
True
Soda
Vegan
Gluten Free
The data is organized as such:
Row 1: Name
Row 2: Calories
Row 3: Sugar
Row 4: Carbs
Row 5: isDrink
Row 6: Description 1
Row 7: Description 2
Row 8: Description 3
Repeat for other items
Descriptions will include Vegan, Vegetarian, Gluten Free and many others (spelled exactly as
shown.)
Menu
After reading the file, you will repeatedly offer the user a menu of actions they can take.
This should be in a loop which ends when the user enters 8.
Actions
mnemonic action
1 Find all vegetarian options
2 Find all Vegan options
3 Find all Gluten Free and Vegan options
4 Find all drink options
5 Find all food options
6 Find food options with 0 carbs and 0 sugar
7 Find food options with less than 100 calories
8 quits the program
Suggestions for functions for you to write
PrintMenu()
This function just prints the menu you see above. Mine has this signature:
void PrintMenu();
GetVegetarian()
This function prints out the food options that are considered vegetarian. Be careful with
what is considered vegetarian. Here is my signature
void GetVegetarian(vector<Food>& foods);
GetVegan()
This function prints out the food options that are considered vegan. Here is my
signature
void GetVegan(vector<Food>& foods);
GetGlutenFreeAndVegan()
This function prints out the food options that are considered Gluten Free and Vegan.
Here is my signature
void GetGlutenFreeAndVegan(vector<Food>& foods);
GetDrinks()
This function prints out the food options that are considered drinks. Here is my signature
void GetDrinks(vector<Food>& foods);
GetFoods()
This function prints out the food options that are not considered drinks.Here is my
signature
void GetFoods(vector<Food>& foods);
GetZeroCarbZeroSugar()
This function prints out the food options that have zero carbs and zero sugar. Here is
my signature
void GetZeroCarbZeroSugar(vector<Food>& foods);
GetFoodLessThan100Calories()
This function prints out the food options that have less than 100.Here is my signature
void GetFoodLessThan100Calories(vector<Food>& foods);

]


That is the assignment

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int text;

int main()
{
ifstream fin;
fin.open("words6.txt");



if (!fin.is_open())
{
cout << "\n File " << " did not open" << endl;
return 1;
}

while (!fin.eof())
{
fin >> text;
cout << text << '\n';
}

struct Food
{

void PrintMenu();

void GetVegetarian(vector<Food>& foods);

void GetVegan(vector<Food>& foods);

void GetGlutenFreeAndVegan(vector<Food>& foods);

void GetFoods(vector<Food>& foods);

void GetZeroCarbZeroSugar(vector<Food>& foods);

void GetFoodLessThank100Calories(vector<Food>& foods);



}

This is what I have so far.
If anyone could help me out that would be great!!
add the data items to your struct. you may also want the struct above main so you can use it inside main. There are ways around that, but its easier to just keep main at the bottom in monolith programs.

your file loop may give troubles. try while(fin>>text){} instead. Sometimes EOF works like you want but it is troublesome as things become more complicated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
something like 
struct food
{
   string name;
   int calories;
   … etc 
   ...functions....
};

int main()
{
    food f;
    while(…)
    {
      fin >> f.name;
      fin >> f.calories; 
     …
    }
}


you will probably have a vector of food type, once you get the basics working, and will read the file into that container of many food items... but to get started, focus on just 1 and forget the file, hard code up one entity and test it and get the methods for the struct right. Once its working for one, then you can make a vector and deal with the file etc. Work from small pieces to bigger, don't do it all at once.
Last edited on
Hello bethmayweather,

I am starting to wonder if you post code just to get someone to fix it for you so that you can call it your own? I am also starting to wonder if you have learned anything?

fin.open("words6.txt"); This is great for the last assignment, but do you not think that a different file name would be better for this assignment.

I have said this before:

PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


Is there anything there that you did not understand. If so say what it is.

I know what you have posted, but I do not know what you started with? This is much better for the instructions:

You by now have lots of practice with built-in types such as float, int, etc. You also
have practice with incorporating these basic types into certain containers such as
vector.

Now comes time to create your own type.

Struct is a means of building a more complicated type from simpler parts. Struct was
introduced in C. In C++, structs were promoted to being nearly identical to the powerful
C++ feature class. In fact, everything you learn in this project about struct can be
applied (with next to no changes) to reimplimentation using class.

Defining a struct:

struct Person
{
   string fname;
   string lname;
   int age;
};

Then, the struct can be used like any type:
// Make one person.
Person p;

// Make a vector of persons.
vector<Person> people;

Accessing members of a struct.
There is more than one syntax for accessing members of a struct. The basic form is
(assuming p as defined above):
cout << p.fname << " " << p.lname << " " << p.age << endl;

The Project
The Struct:
You will need to define your own struct. I called mine Food. Your struct must contain these
elements: the name of the food, the number of calories, the amount of sugar as a number, the
number of carbs, true or false of whether it is a drink, and a list of descriptions describing the
food such as Vegetarian.

The Data:
The data will be read in from a file. You will need to create your own data file that matches the
format described below.

Cool Ranch Doritos
150
1
18
False
Snack
Chips
Vegetarian
Coca-Cola
240
65
65
True
Soda
Vegan
Gluten Free

The data is organized as such:
Row 1: Name
Row 2: Calories
Row 3: Sugar
Row 4: Carbs
Row 5: isDrink
Row 6: Description 1
Row 7: Description 2
Row 8: Description 3

Repeat for other items
Descriptions will include Vegan, Vegetarian, Gluten Free and many others (spelled exactly as
shown.)

Menu
After reading the file, you will repeatedly offer the user a menu of actions they can take.
This should be in a loop which ends when the user enters 8.

Actions
mnemonic action
1 Find all vegetarian options
2 Find all Vegan options
3 Find all Gluten Free and Vegan options
4 Find all drink options
5 Find all food options
6 Find food options with 0 carbs and 0 sugar
7 Find food options with less than 100 calories
8 quits the program

Suggestions for functions for you to write:

PrintMenu()
This function just prints the menu you see above. Mine has this signature:
void PrintMenu();

GetVegetarian()
This function prints out the food options that are considered vegetarian. Be careful with
what is considered vegetarian. Here is my signature:
void GetVegetarian(vector<Food>& foods);

GetVegan()
This function prints out the food options that are considered vegan. Here is my
signature:
void GetVegan(vector<Food>& foods);

GetGlutenFreeAndVegan()
This function prints out the food options that are considered Gluten Free and Vegan.
Here is my signature:
void GetGlutenFreeAndVegan(vector<Food>& foods);

GetDrinks()
This function prints out the food options that are considered drinks. Here is my signature:
void GetDrinks(vector<Food>& foods);

GetFoods()
This function prints out the food options that are not considered drinks.Here is my
signature:
void GetFoods(vector<Food>& foods);

GetZeroCarbZeroSugar()
This function prints out the food options that have zero carbs and zero sugar. Here is
my signature:
void GetZeroCarbZeroSugar(vector<Food>& foods);

GetFoodLessThan100Calories()
This function prints out the food options that have less than 100.Here is my signature
void GetFoodLessThan100Calories(vector<Food>& foods);


They are very good instructions if you break them up into something understandable.

jonnin has made some good points that you need to work with.

Like any program it is best to start with the simple parts first. The ones that you need the most like:
● struct
● menu I would put this in a function.
● vector (of structs).
● reading the file.
● Put the information into the struct (this should go with reading the file).
● Put the struct in the vector.
Now you have something to work with.

Work up code for that and the rest should be easier to figure out.

There is a lot of useful information in http://www.cplusplus.com/forum/beginner/264950/ Do not forget about what was done there.

Hope that helps,

Andy
#include <iostream>
#include <fstream>
#include <vector>
#include <string>


using namespace std;
void PrintMenu();

struct Food
{
string name;
int calories;
int sugar;
int carbs;
bool isDrink;
vector<string>descriptions;

};

int main()
{
string food;
string temp;

ifstream fin;

fin.open("food.txt");

if (!fin.is_open())
{
cout << "\n File " << "did not open" << endl;
return 1;
}

while (fin.is_open())
{
getline(fin, temp);

Food f;
f.name = temp;

getline(fin, temp);

f.calories = stoi(temp);

f.sugar = stoi(temp);

f.carbs = stoi(temp);

f.isDrink = stoi(temp);

f.descriptions.push_back(temp);

f.descriptions.push_back(temp);

f.descriptions.push_back(temp);


}

while (true)
{
PrintMenu();

string answer;
cin >> answer;
}
}

void PrintMenu()
{
cout << "Menu" << endl;
cout << " 1 Find all Vegetarian options " << endl;
cout << " 2 Find all Vegan options " << endl;
cout << " 3 Find all Gluten Free and Vegan options " << endl;
cout << " 4 Find all drink options " << endl;
cout << " 5 Find all food options " << endl;
cout << " 6 Find all food options with 0 carbs and 0 sugar " << endl;
cout << " 7 Find all food options with less than 100 calories " << endl;
cout << " 8 Quits the program " << endl;
}

This is what I have so far, but my program won't run. I was able to open the file I'm using but it says there are build errors within my struct. I'm not sure what they are.
Hello bethmayweather,

This is what I have so far, but my program won't run.
Why Not?

I wish I could tell you , but you neglected to mention what is not working or to post the exact error messages that you are getting.

I was able to open the file I'm using but it says there are build errors within my struct. I'm not sure what they are.
If you are not sure post the error messages that you receive.

No where in the instructions did I get the idea that the struct should contain a vector of descriptions, but if that is what you want that is OK.

I did have the understanding that you should create a vector of structa to hold all the information of each record of the file.

Your code for opening the file stream works, but I did show you a different way in http://www.cplusplus.com/forum/beginner/264950/#msg1141282 lines 22 - 31. I was hoping that some of that would stick in your memory.

In the first while to read the file the while condition will not work the way that you are thinking. See above ling lines 33 - 39.

Also there are 9 lines for each record of the input file, so why are you only reading two of those lines?

The "stoi" function is not needed for all those variables. As an example you could use fin >> calories >> sugar >> carbs >> std::boolalpha >> isDrink;. The "std::boolalpha" comes from the "iostream" header file and is a way of changing text to a number or a number to text. In the input file "True" and "False" will have to be changed to all lower case letters for this to work otherwise you will have to read this as a string then set a bool variable.

The second while is an endless loop the will print the menu, wait for you to enter something from the keyboard and then so it all over again. Not what you want.

It is a fair start, but you are not doing everything that you need to do.

Previously I said:

Like any program it is best to start with the simple parts first. The ones that you need the most like:
● struct
● menu I would put this in a function.
● vector (of structs).
● reading the file.
● Put the information into the struct (this should go with reading the file).
● Put the struct in the vector.
Now you have something to work with.



When I started working on the program I ended up doing things in this order:

● struct
● vector (of structs).
● reading the file.
● Put the information into the struct (this should go with reading the file).
● Put the struct in the vector.
● menu I would put this in a function.


In my menu function I put the menu in a do/while loop, entered the menu choice there and verified that it is a proper choice. Then finished the function by returning the menu choice, when it is valid, back to main where I could use it.

You have a fair start, but it needs some work. Mostly on reading the file and putting what you have read into a vector.

I went about reading the file and storing that information inot a vector in a completely different way. Looking back I realize what I did may be farther ahead of what you have learned do far.

You have covered most of what needs to be done for the first part. You just need to get it to read the file correctly without all the extra work.

Hope that helps,

Andy
Hello bethmayweather,

When you print you menu this might make it easier to work with:
1
2
3
4
5
6
7
8
9
10
11
	std::cout
	<< "\n"
	<< " 1. Find all vegetarian options\n"
	<< " 2. Find all Vegan options\n"
	<< " 3. Find all Gluten Free and Vegan options\n"
	<< " 4. Find all drink options\n"
	<< " 5. Find all food options\n"
	<< " 6. Find food options with 0 carbs and 0 sugar\n"
	<< " 7. Find food options with less than 100 calories\n"
	<< " 8. Exit\n"
	<< " Enter choice: ";

You do not need to put a "std::endl" at the end of every line and the "std::cin" will flush the output buffer before the "cin" is used.

Just something I found that saves some time when coding. Writing it this way you only have one "cout" statement to work with.

Hope that helps,

Andy

Edit: typo.
Last edited on
#include <iostream>
#include <fstream>
#include <vector>
#include <string>


using namespace std;
void PrintMenu();

struct Food
{
string name;
int calories;
int sugar;
int carbs;
bool isDrink;
vector<string>descriptions;

};

int main()
{
string food;
string temp;

ifstream fin;

fin.open("food.txt");

if (!fin.is_open())
{
cout << "\n File " << "did not open" << endl;
return 1;
}

while (fin.is_open())
{
getline(fin, temp);

Food f;
f.name = temp;

getline(fin, temp);

f.calories = stoi(temp);

getline(fin, temp);

f.sugar = stoi(temp);

getline(fin, temp);

f.carbs = stoi(temp);

getline(fin, temp);

f.isDrink = stoi(temp);

getline(fin, temp);

f.descriptions.push_back(temp);

getline(fin, temp);

f.descriptions.push_back(temp);

getline(fin, temp);

f.descriptions.push_back(temp);


}

while (true)
{
PrintMenu();

string answer;
cin >> answer;
}
}

void PrintMenu()
{
cout << "Menu" << endl;
cout << " 1 Find all Vegetarian options " << endl;
cout << " 2 Find all Vegan options " << endl;
cout << " 3 Find all Gluten Free and Vegan options " << endl;
cout << " 4 Find all drink options " << endl;
cout << " 5 Find all food options " << endl;
cout << " 6 Find all food options with 0 carbs and 0 sugar " << endl;
cout << " 7 Find all food options with less than 100 calories " << endl;
cout << " 8 Quits the program " << endl;

}


This is what I have now and my program doesn't run, I'm not sure where the issue is though
Hello bethmayweather,

Last time.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


If you can not learn from this, how can I expect you to learn anything?

This is what I have now and my program doesn't run, I'm not sure where the issue is though

Since you did not bother to explain what it is doing I can only guess at your problem.

Looking at the program you start in "main" defining the variable string food, but you never use it. Is there a point or reason for this variable?

After that you are usable down to the while loop, but you have see better code for this part.

The while condition is based on "fin.is_open()". You should read http://www.cplusplus.com/reference/fstream/ifstream/is_open/ for an understanding of how this works. Even when "fin" sets the "eof" bit on the stream the condition still evaluates to true.

I do not know where you got the idea of reading the file using "getline" for every line and then using "stoi" to convert the numeric variables. I am wondering if you could find a more difficult way of doing this? Although it does work until you reach the line for "is drink". You read this as a string with the "getline" and it works because it is a string, but when yo try to convert to an int, which is wrong in the first place because "isDring" is defined as a bool, the "stoi" function fails because it can not convert a string of letters to a number. This should result in a run time error of "Invalid stoi arguement".

Maybe I should have stated this in a better way:
1
2
3
4
5
6
7
8
9
10
11
12
while (fin.is_open())  // <--- This does not work the way you are thinking.
{
	Food f; // <--- Should use something better than just 'f'. I called it "foodItem".

	getline(fin, temp);

	f.name = temp;

	fin >> foodItem.calories >> foodItem.sugar >> foodItem.carbs >> std::boolalpha >> foodItem.isDrink;

	// <--- Clears the "\n" from the input buffer before the next "getline". A must have.
	fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>. 

Line 9 will read and store four fields at one time.

As I said in the input file "True" and "False" must be in all lower case letters for the "std::boolalpha" to work. Should you need the "std::boolalpha" for output it will take the number stored in the "bool" variable and change it to a word.

The rest of reading the file does work as is. I do personally feel the storing the three descriptions in a vector is a bit much, but it does work if that is what you want. And it is good practice.

Now that you have stored all the information from the file what are you going to do with it. The next time through the loop you will overwrite what you have just read and will have no way to use The first read. In the end the struct will only contain information from the last read.

Your instructions start with:

Struct is a means of building a more complicated type from simpler parts. Struct was
introduced in C. In C++, structs were promoted to being nearly identical to the powerful
C++ feature class. In fact, everything you learn in this project about struct can be
applied (with next to no changes) to reimplimentation using class.

Defining a struct:

struct Person
{
   string fname;
   string lname;
   int age;
};

Then, the struct can be used like any type:
// Make one person.
Person p;  // <--- But give it a better name.

// Make a vector of persons. This should be done in "main".
vector<Person> people;

Accessing members of a struct.
There is more than one syntax for accessing members of a struct. The basic form is
(assuming p as defined above):
cout << p.fname << " " << p.lname << " " << p.age << endl;


This is good information and good examples for constructing the struct and how to use it. But remember that they are just examples and does not mean that you have to follow them exactly. Calling the actual object that is constructed "p", or "f" as you did, is only a suggestion. It also strikes me as being lazy and unimaginative in choosing a variable name. You should strive to come up with a better name than a single letter for the variable name. It mostly benefits you in the future and the end.

You do seem to grasp accessing the member variables of the struct properly.

Once you get the read loop fixed the next while loop is another endless loop the just prints the menu and waits for you to type something in, does not matter what, and then loops back to the top. I used a do/while loop here, but a while loop can work if done correctly.

For now I would comment these lines and worry about the loop later.
1
2
3
4
5
6
7
//while (true)
//{
	PrintMenu();

	string answer;
	cin >> answer;
//} 


Hope that helps,

Andy
Thank you! Right now it is giving me four warnings that say my variables are uninitialized at line 22. I'm not sure how to fix it
that isnt an error, its a warning.
its good practice to init variables, though, so it warns you.

you fix it like this:
somewhere you have something like
int x;

and you should make it
int x = 0; //or some other useful value
can even be a function call, etc: I prefer to init to the first value it will get so it is usable right away when possible, eg
int x = foo();
Last edited on
PLEASE learn to use code tags, it makes reading and commenting on your code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/

HINT: You can edit your post and add the tags.

giving me four warnings that say my variables are uninitialized at line 22

If you used code tags we'd know what line 22 is, and could help you.
Hello bethmayweather,

Right now it is giving me four warnings that say my variables are uninitialized at line 22


That is nice, but my line 22s say
22
23
void GetDrinks(std::vector<Food>& items);

and
22
23
{
, which is the opening brace of "main".

So which line 22 is giving you a problem? And which variables?

The warnings will not keep the program from running, but they do need fixed.

The only variables I can think of are in the struct and you can just set them to (0) zero.

I did manage to get your code to do this:

                         MENU
-------------------------------------------------
 1. Find all vegetarian options
 2. Find all Vegan options
 3. Find all Gluten Free and Vegan options
 4. Find all drink options
 5. Find all food options
 6. Find food options with 0 carbs and 0 sugar
 7. Find food options with less than 100 calories
 8. Quits the program
 Enter choice: 4

 Coca-Cola
 Pepsi Cola
 Diet Pepsi Cola

                         MENU
-------------------------------------------------
 1. Find all vegetarian options
 2. Find all Vegan options
 3. Find all Gluten Free and Vegan options
 4. Find all drink options
 5. Find all food options
 6. Find food options with 0 carbs and 0 sugar
 7. Find food options with less than 100 calories
 8. Quits the program
 Enter choice: 5

 Cool Ranch Doritos
 Coca-Cola
 Pepsi Cola
 Diet Pepsi Cola
 Chex Mix Bold Party Blend

                         MENU
-------------------------------------------------
 1. Find all vegetarian options
 2. Find all Vegan options
 3. Find all Gluten Free and Vegan options
 4. Find all drink options
 5. Find all food options
 6. Find food options with 0 carbs and 0 sugar
 7. Find food options with less than 100 calories
 8. Quits the program
 Enter choice:


The names are from what I happened to have around.

Hope that helps,

Andy
So my code does work?
Hello bethmayweather,

I had to change a lot to make it work, but it is fixable.

To Start with I got rid of all the "stoi" conversions and especially the f.isDrink = stoi(temp); as it does not work at all and will cause a run time error when it tries to convert a "string" to an "int".

Once I got the read working properly the rest pretty much fell into place.

While I am thinking about it while (fin.is_open()). Does not work . It just creates an endless loop until the stream is closed. If I did not mention the before http://www.cplusplus.com/reference/fstream/basic_ifstream/is_open/

The while loop at the end of "main" I changed to a do/while loop and used a switch for the menu choice.

As for the functions for the menu choices I think I just wrote my own. I would have to look back and see if you did anything.

Andy
Topic archived. No new replies allowed.