views:

29

answers:

2

I have a simple function in my program, when I was wanting to mess around with unicode and do stuff with it. In this function, I wished to display the code value of the character the user entered. It SEEMED possible, here's my function:

wstring listcode(wchar_t arg) {
    wstring str = L"";
    str += static_cast<int> (arg); //I tried (int) arg as well
    str += L": ";
    str += (wchar_t) arg;
    return str;
}

Now as you see I just wanted to display the integer value (like an ascii character, such as (int) "a"), but something like listcode(L"&") will be displayed as &: & !

Is it not possible to find the integer value of a wide character like that?

+3  A: 

In C++, you cannot add anything to strings but characters and other strings. There is no implicit conversion from int (or anything else) to string. That's just the way the string type is designed.
What you do instead is to use string streams:

std::wstring listcode(wchar_t arg)
{
  std::wostringstream oss;
  oss << static_cast<int>(arg);
  oss << L": ";
  oss << arg;
  return oss.str();
}

In practice, however, when converting to strings in C++, it's better to have functions writing to a stream, than returning a string:

void listcode(std::wostream os, wchar_t arg)
{
  os << static_cast<int>(arg);
  os << L": ";
  os << arg;
}

That way, if you want to output something to the console or to a file, you can directly pass std::cout or a file stream, and if you want a string, you just pass a string stream.

sbi
A: 

operator+= doesn't take an int so it's automatically converted. You could use a wostringstream for the conversion:

#include <iostream>
#include <sstream>
#include <string>
std::wstring listcode(wchar_t wc) {
    std::wostringstream woss;
    woss << static_cast<int>(wc);
    woss << ": " << wc;
    return woss.str();
}

int main() {
    wchar_t wc = L'&';
    std::wcout << listcode(wc) << std::endl;
}
Kleist