c++: stringstream to vector

user459811 picture user459811 · Mar 8, 2011 · Viewed 12k times · Source

I'm trying to store the data that is in a stringstream into a vector. I can succesfully do so but it ignores the spaces in the string. How do I make it so the spaces are also pushed into the vector?

Thanks!

Code stub:

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

using namespace std;

int main()
{
    stringstream s;
    string line  = "HELLO HELLO\0";

    stringstream stream(line);

    unsigned char temp;
    vector<unsigned char> vec;
    while(stream >> temp) 
        vec.push_back(temp);


    for (int i = 0; i < vec.size(); i++)
         cout << vec[i];
    cout << endl;
    return 0;
}

Answer

Jeremiah Willcock picture Jeremiah Willcock · Mar 8, 2011

Why are you using a stringstream to copy from a string into a vector<unsigned char>? You can just do:

vector<unsigned char> vec(line.begin(), line.end());

and that will do the copy directly. If you need to use a stringstream, you need to use stream >> noskipws first.