1

Given the following code:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

int main()
{
    std::stringstream istrs("1 2 3 4 5 6");
    std::vector<int> vec;
    while(!istrs.eof())
    {
        int temp;
        std::stringstream o;
        istrs.get(*o.rdbuf(), ' ');
        o >> temp;
        vec.push_back(temp);
    }
    for(auto a : vec)
        std::cout << a << " ";
    std::cout << std::endl;
}

Why does the loop never exit? Why does o remain uninitialized? I'm trying to split the ifstream buffer into smaller chunks for processing but I don't know why this get() doesn't work like I thought it would.

kiroma
  • 91
  • 6
  • Please also read [this](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) on why not to use `while (!istrs.eof())` (consider using `while (istrs)` instead) – hlt Sep 21 '18 at 10:05

1 Answers1

0

You could modify your code to parse the string using the getline for example:

   std::stringstream istrs("1 2 3 4 5 6");
    std::vector<int> vec;
    string temp;
    while(getline(istrs,temp, ' '))
    {
        vec.push_back(stoi(temp));
    }
    for(auto a : vec)
        std::cout << a << " ";
    std::cout << std::endl;

I do not see the need for another stringstream and then a conversion.

To see why what you mentioned fails, refer to the documentation of stringstream and for get. We are dealing with the 6th overload of signature type basic_istream& get( basic_streambuf& strbuf, char_type delim );

reads characters and inserts them to the output sequence controlled by the given basic_streambuf

You are storing that as an int, try declaring temp as string, get the string using the stream operator o >> temp, and do a conversion to int using stoi. You will find the conversion you will succeed for the first time and not the others, rather the program will crash. The reason is after 1, you extract no characters and satisfy the condition:

the next available input character c equals delim, as determined by Traits::eq(c, delim). This character is not extracted.

In which case

If no characters were extracted, calls setstate(failbit).

In your while loop if you set !istrs.eof() && istrs.good(), you will see the program will terminate gracefully but you will only have one value.

Samer Tufail
  • 1,755
  • 11
  • 23