tmighty
tmighty

Reputation: 11399

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);

Upvotes: 4

Views: 7269

Answers (4)

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

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));

Upvotes: 12

user1744056
user1744056

Reputation:

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);

Upvotes: 3

ArgumentNullException
ArgumentNullException

Reputation: 71

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

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

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.

Upvotes: 0

Related Questions