1

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.

2
  • On a side note: consider using std::strtod() or std::stod() to parse your string values into doubles, instead of using stringstream. And you don't need to swap() a stringstream to clear its data, you can use its str() method instead to assign a blank string. And you certainly don't need to swap()/clear() a container variable that will be going out of scope afterwards. Commented Mar 6, 2019 at 0:57
  • @RemyLebeau duly noted! I was thinking of using 'std::stod()' before however there were some troubles with it so i decided to whip up a temporary solution using stringstream Commented Mar 6, 2019 at 11:20

1 Answer 1

2

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)){
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.