Alex Rivera | Logout

c++: stringstream to vector

Asked 2011-03-07T23:07:29.663
12

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;
}
Edit
Report

1 Answer

17

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.

answered 2011-03-07T23:18:19.660

Your Answer