简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM