Convert vector {1,2,3} into string “1-2-

2019-01-29 03:37发布

问题:

I want to display numbers in a std::vector<unsigned char> on a screen, but on its way to the recipient, I need to stuff these numbers into a std::string.

Whatever I tried (atoi, reinterpret_cast, string.c_str() ...), gave me either a nonsense, or a letter representation of those original numbers - i.e. their corresponding ascii characters.

So how do I easily (preferably standard method) convert vector<unsigned char> {1,2,3} into a string "1-2-3"?

In the Original Post (later edited) I mentioned, that I could do that in C# or Java. Upon the request of πάντα ῥεῖ to provide example in C# or Java, here is a quick Linq C# way:

    public static string GetStringFromListNumData<T>(List<T> lNumData)
    {
        // if (typeof(T) != typeof(IConvertible)) throw new ArgumentException("Expecting only types that implement IConvertible !");
        string myString = "";
        lNumData.ForEach(x => myString += x + "-");
        return myString.TrimEnd('-');
    }

回答1:

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;


回答2:

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


回答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);
});