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.