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;
}
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With