简体   繁体   中英

C++ append unsigned char to wstring

I want to append an unsigned char to a wstring for debugging reasons.

However, I don't find a function to convert the unsigned char to a wstring, so I can not append it.

Edit: The solutions posted so far do not really do what I need. I want to convert 0 to "0". The solutions so far convert 0 to a 0 character, but not to a "0" string.

Can anybody help?

Thank you.

unsigned char SomeValue;
wstring sDebug;

sDebug.append(SomeValue);

The correct call for appending a char to a string (or in this case, a wchar_t to a wstring) is

sDebug.push_back(SomeValue);

Documentation here .

To widen your char to a wchar_t, you can also use std::btowc which will widen according to your current locale.

sDebug.push_back(std::btowc(SomeValue));

Just cast your unsigned char to char:

sDebug.append(1, static_cast<char>(SomeValue));

And if you want to use operator+ try this:

sDebug+= static_cast<char>(SomeValue);

Or even this:

 sDebug+=boost::numeric_cast<char>(SomeValue);

There's an overload of append that also takes the number of times to append the given character:

sDebug.append(1, SomeValue);

However, this will result in a conversion between unsigned char and wchar_t . Perhaps you want SomeValue to be a wchar_t .

wstring has a constructor that takes a char. That would create a wstring from a char which you can then append.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM