Hello, I have some weird problem with this code.
The problem is that when I use >> to read data a text file to vector. It will only add the first double and discard the rest. Anyway if I use array instead of vector it works fine. Anyone know what the problem can be? I've used cout to check whetever it sends in correct data or not. And it does send in correct data.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Demo {
string name;
double points;
vector<double> test;
// double test[2];
};
istream& operator>> (std::istream& in, Demo &d);
istream& operator>> (std::istream& in, vector<double> d);
//istream& operator>> (istream& in, double d[]);
int main()
{
vector<Demo> d;
Demo tmp;
while(cin >> tmp) {
d.push_back(tmp);
}
cout << d[0].name << ", " << d[0].points << ", " << d[0].test[0] << ", " << d[0].test[1] << endl;
cout << d[1].name << ", " << d[1].points << ", " << d[1].test[0] << ", " << d[1].test[1] << endl;
cout << d[2].name << ", " << d[2].points << ", " << d[2].test[0] << ", " << d[2].test[1] << endl;
cout << d[3].name << ", " << d[3].points << ", " << d[3].test[0] << ", " << d[3].test[1] << endl;
cout << d[4].name << ", " << d[4].points << ", " << d[4].test[0] << ", " << d[4].test[1] << endl;
cout << d[5].name << ", " << d[5].points << ", " << d[5].test[0] << ", " << d[5].test[1] << endl;
return 0;
}
istream& operator>> (std::istream& in, Demo &d) {
getline(in, d.name);
in >> d.points;
in >> d.test;
return in;
}
std::istream& operator>> (std::istream& in, vector<double> d) {
double x;
d.clear();
for(int i = 0; i < 2; i++) {
in >> x;
d.push_back(x);
}
in.ignore();
return in;
}
//istream& operator>> (istream& in, double d[]) {
// for(int i = 0; i < 2; i++) {
// in >> d[i];
// }
// in.ignore();
// return in;
//}
the text file I use contains
Mario Pizza
2.3 159.9 1
Luigi Kebab
2.6 169.5 2
Princess Peach
2.6 169.5 3
Link Hylia
2.6 169.5 4
Zelda Hyrule
2.6 169.5 5