Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: stringstream to vector

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;
}
like image 964
user459811 Avatar asked Mar 07 '11 23:03

user459811


3 Answers

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.

like image 99
Jeremiah Willcock Avatar answered Nov 10 '22 05:11

Jeremiah Willcock


By default, the standard streams all skip whitespace. If you wish to disable the skipping of white space you can explicitly do so on the next stream extraction (>>) operation by using the noskipws manipulator like so:

stream >> std::noskipws >> var;
like image 45
diverscuba23 Avatar answered Nov 10 '22 04:11

diverscuba23


I'm inclined to suggest just using the container that you actually want but you could also use the manipulator noskipws

See this for more info on stringstream and other methods you could use besides the extraction operator

Edit:

Also consider std::copy or std::basic_string<unsigned char> for simplicity.

like image 45
AJG85 Avatar answered Nov 10 '22 04:11

AJG85