我有一串字节,如下所示:
"1,3,8,b,e,ff,10"
我如何将此字符串拆分为包含以下值的 BYTE 的 std::vector:
[0x01、0x03、0x08、0x0b、0x0e、0xff、0x10]
我正在尝试使用“,”作为分隔符来拆分字符串,但我在使用它时遇到了一些问题。有人可以帮我解决这个问题吗?
所以我试过这个:
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);
}
但这会将 ascii 字节值推送到 vector 中:
49 //1
51 //3
56 //8
98 //b
101 //e
102 //f
102 //f
49 //1
48 //0
我试图用以下内容填充 vector :
0x01
0x03
0x08
0x0b
0x0e
0xff
0x10
最佳答案
您只是缺少适应 linked answer 的用例中出现的一些小问题来 self 的评论:
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
}
}
您可以看到完整的示例 here on ideone .
关于c++ - 在 C++ 中将字节字符串拆分为 BYTES vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938606/