user3823821
user3823821

Reputation: 91

c++ How to istream struct contains vector

How to istream struct that contains vector of integer as member, I tried the following code but it failed to read the file

struct Ss{
    std::vector<int> a;
    double b;
    double c;    };

std::istream& operator>>(std::istream &is, Ss &d)
{
    int x;
    while (is >> x)  
        d.a.push_back(x);
    is >> d.b;
    is >> d.c;
    return is;
}
std::vector <std::vector<Ss >> Aarr;

void scanData()
{
    ifstream in;
    in.open(FileInp);
    std::string line;


    while (std::getline(in, line))
    {
        std::stringstream V(line);
        Ss S1;
        std::vector<Ss > inner;
        while (V >> S1)
            inner.push_back(std::move(S1));
        Aarr.push_back(std::move(inner));

    }
}

I did search for similar problems but i could not find one.

Upvotes: 0

Views: 208

Answers (1)

Fred Larson
Fred Larson

Reputation: 62073

The immediate problem here is that the same condition that terminates your while loop prevents the successive reads from working. The stream is in an error state. So your double values are never read.

Actually, the integer part of the first double is read as an integer, leaving the fractional part in the stream. You can't recover from this.

One way to solve this might be to read in your values as strings, converting them to integers using stoi and putting them in the vector. But before you do the integer conversion, check for a decimal point in the string. If it contains one, break out of the loop. Convert the double values using stod.

Upvotes: 1

Related Questions