c++ - 在 C++ 中将字节字符串拆分为 BYTES vector

标签 c++ string split byte delimiter

我有一串字节,如下所示:

"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/

相关文章:

java - Java中String CompareTo函数的时间复杂度是多少?

c - 标记多个字符串 C

java - 使用不同的字符和模式分割字符串

c++ - 将文件读入结构 (c++)

c++ - "Spybot Search & Destroy"应用程序使用了哪个 GUI 框架?

c++ - 为什么有些包含需要 .h 而有些则不需要?

c++ - 为什么要用友元函数来定义比较运算符?

java - "Must be of an array type but is resolved to string"....为什么以及如何修复它?

Python positive-lookbehind 拆分可变宽度

javascript - 从字符串中删除元素并连接它的更好方法是什么?