Let's say I have a .dat file called numbers.dat
which consists of a list of integers like so:
1
44
2
5
and so on.
Then to read from this .dat file and place each number in a vector of type int
, I know what to do:
std::ifstream file("numbers.dat");
int x;
std::vector<int> integers;
while(file >> x)
{
integers.push_back(x);
}
file.close
Now if I want to output each integer I just need to loop over the vector, doing a cout
each time.
But in my case, I have a .dat file called food.dat
with multiple data types on each line separated by tab characters, for example
Eggs Eg 1 1.2
Spam Spm 2 1.5
and so on.
I have created a class called Food, with the fields name
, symbol
, number
, and cost
, which are of type string
, string
, int
, and double
respectively. Now, if I try the same as before, but with the appropriate changes:
std::ifstream file("food.dat");
Food f; // the constructor for Food handles default values
std::vector<Food> vec;
while(file >> f)
{
vec.push_back(f);
}
file.close;
I get the compiler error:
error: invalid operands to binary expression('std::ifstream' (aka 'basic_ifstream<char') and Food)
while (file >> f)
So I tried something else, this time I am just trying to read the first line in the file to check that it works.
std::ifstream file("food.dat");
Food f;
file >> f;
file.close();
But this gives the same compiler error as before. I have found that the code snippet file >> f
is the part that the compiler complains about in both cases.
How can I avoid this error and make the code compile? My intention is to output each element of the vector (I have already correctly overloaded the <<
operator to handle this for variables of type Food).
Should I overload the "get from" operator, >>
for variables of type Food in order to make the code compile?
How can I avoid this error and make the code compile?
You need to define a function
std::istream& operator>>(std::istream& in, Food& f) { ... }
appropriately.
E.g.
std::istream& operator>>(std::istream& in, Food& f)
{
return in >> f.name >> f.symbol >> f.number >> f.coset;
}