Search code examples
c++while-loopgetline

While Loop looping only once when using getline from file


I have this small bit of code:

fileopen.open(file_name);
while (getline(fileopen, line, ',')){
    string temp;
    vector<string> mug;
    temp = line;
    stringstream ss(temp);
    while (getline(ss, temp, ' ')){
        mug.push_back(temp);
    }
    stringstream conv;
    double vol, cos;
    conv << mug.at(1);
    conv >> vol;
    stringstream().swap(conv);
    conv << mug.at(3);
    conv >> cos;
    mugs.push_back(make_tuple(mug.at(0), vol, mug.at(2), cos));
    stringstream().swap(conv);
    stringstream().swap(ss);
    temp.clear();
}
sort(mugs.begin(), mugs.end(), sort_by);
for (int i = 0; i < mugs.size(); i++){
    cout << "Country: " << get<0>(mugs[i]) << " ";
    cout << ", Volume: " << get<1>(mugs[i]) << " ";
    cout << ", Material: " << get<2>(mugs[i]) << " ";
    cout << ", Price: " << get<3>(mugs[i]) << "\n";
}

I have multiple clears and stringstream().swap()'s because it is a well known issue. <sstream> seems to interrupt iterations for while loops. However, even this doesn't seem to be working. The input given from the file is as follows:

RUS 0.1 Wood 20
USA 0.4 Glass 0.5

The current code prints the first line as needed, but fails to iterate and print the second line. Any suggestions?

I have tried using continue and goto for solving this problem. None of those solutions have worked out.


Solution

  • The input file, as posted, does not have , in any of the lines. Hence, use of

    while (getline(fileopen, line, ',')){
    

    does not make sense. Use

    while (getline(fileopen, line)){