I want to display numbers in a std::vector
on a screen, but on its way to the recipient, I need to stuff these numbers into a std::st
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);
});
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
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;