Convert vector<unsigned char> {1,2,3} into string “1-2-3” AS DIGITS

北城以北 提交于 2019-11-29 17:02:53

Simply use a std::ostringstream:

std::vector<unsigned char> v{1,2,3};
std::ostringstream oss;
bool first = true;
for(auto x : v) {
    if(!first) oss << '-'; 
    else first = false;
    oss << (unsigned int)x;
}
std::cout << oss.str() << std::endl;

Here is how I handle that:

std::vector<unsigned char> v {1, 2, 3};

std::string s; // result

auto sep = ""; // continuation separator
for(auto n: v)
{
    s += sep + std::to_string(n);
    sep = "-"; // change the continuation separator after first element
}

std::cout << s << '\n';

The continuation separator starts out empty and gets changed after concatenating the first output.

Output:

1-2-3

Yet, another example:

std::vector<unsigned char> v{1,2,3};

std::ostringstream str;
std::transform(v.begin(), v.end(), std::ostream_iterator<char>(str, "-"), [](unsigned char c){ return '0' + c;});

std::cout << str.str();

[edit]

unfortunately above will add additional trailing - symbol, to prevent it - more complicated code is necessary:

std::transform(v.begin(), v.end(), std::ostream_iterator<std::string>(str), [&](auto c){
    return (str.rdbuf()->in_avail() ? "-" : "") + std::to_string(c);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!