I have a string of bytes that looks like the following:
"1,3,8,b,e,ff,10"
How would I split this string into an std::vector of BYTEs containing the following values:
[ 0x01, 0x03, 0x08, 0x0b, 0x0e, 0xff, 0x10 ]
I'm trying to split the string using ',' as the delimiter, but I'm having some trouble getting this to work. Can someone give me a helping hand on how to accomplish this?
So I have tried this:
std::istringstream iss("1 3 8 b e ff 10");
BYTE num = 0;
while(iss >> num || !iss.eof())
{
if(iss.fail())
{
iss.clear();
std::string dummy;
iss >> dummy;
continue;
}
dataValues.push_back(num);
}
But this pushes the ascii byte values into the vector:
49 //1
51 //3
56 //8
98 //b
101 //e
102 //f
102 //f
49 //1
48 //0
I'm instead trying to fill the vector with:
0x01
0x03
0x08
0x0b
0x0e
0xff
0x10
You've just been missing to adapt some small issues appearing with your use case for the linked answer from my comment:
std::istringstream iss("1,3,8,b,e,ff,10");
std::vector<BYTE> dataValues;
unsigned int num = 0; // read an unsigned int in 1st place
// BYTE is just a typedef for unsigned char
while(iss >> std::hex >> num || !iss.eof()) {
if(iss.fail()) {
iss.clear();
char dummy;
iss >> dummy; // use char as dummy if no whitespaces
// may occur as delimiters
continue;
}
if(num <= 0xff) {
dataValues.push_back(static_cast<BYTE>(num));
}
else {
// Error single byte value expected
}
}
You can see the fully working sample here on ideone.
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