Reading a text and storing it into a vector with different variables.

Hi there, I have an issue I need some help with. So basically, I have these saved text files from the vectors in my program and they show as :
Pizza.txt

Hawaiian RM12.00
Pepperoni RM12.00

They are in the format of my food class.

class food
{
string name;
float price;
public:
food (string name, double price) : name(name), price(price) {}~~
~~~~~~~~
}

vector<food> orderpizza;

Now , I need to be able to re-load the text files into my program again into the very same vector. After browsing about, I'm still unsure on how to allow the program to recognize which is the name and which is the price. This is what I have so far:

A function inside the food class:
class Food
{~~
void readFile(string file, vector<food> vec, ifstream &readfile)
{
string name;
double price;

readfile.open(file.c_str());

while (readfile >> name >> price)
{

vec.push_back(name, price);
}

readfile.close();
}
}

and then I call:

readFile("Pizza.txt", orderpizza, readfile);

Error I'm getting :
In member function 'void food::readFile(std::string, std::vector<food>, std::ifstream&)':|
no matching function for call to 'std::vector<food>::push_back(std::string&, double&)'|

If anyone can help me out. Thanks.

You're getting the error because vector<T>::push_pack() takes only one argument: an object (of type T) to store. In this case it expects a 'food' object, but you're passing two arguments, both of the wrong type.

What you are doing can be accomplished using emplace_back() but it requires C++11 support (should not be a problem by now!)
http://www.cplusplus.com/reference/vector/vector/emplace_back/
emplace_back() takes all the arguments passed to it, contructs an object for you with them and puts it in the vector

I'm still unsure on how to allow the program to recognize which is the name and which is the price
Read two words. The first is the name and the second is the price. Treat the variables where you store them accordingly.

-----
You don't need that ifstream& parameter. The file is opened at the beginning of the function and closed at the end. Since you don't need it anymore when you return, you might as well make it a local variable.
-----
Please enclose code in code tags to preserve readability ("Source code" button on the right).
Props for posting the compiler error.
Last edited on
Topic archived. No new replies allowed.