1

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?

John D.
  • 265
  • 4
  • 10
  • I think you just shouldn't += an int to a wstring without converting it to a string representation. – wRAR Jun 30 '10 at 05:18
  • It works fine returning just an int. – John D. Jun 30 '10 at 05:22
  • No, just convert (int)arg to a wstring before adding it to str (I don't know how to do that in C++ correctly). – wRAR Jun 30 '10 at 05:24
  • 1
    @wRAR: But that's what the question is all about. – sbi Jun 30 '10 at 05:34
  • 2
    `wchar_t` does not always represent single code point. if `sizeof(wchar_t)` is 4 (on all POSIX platforms) then it represents one, but if `sizeof(wchar_t)` is 2 (on Windows) it does not as Unicode code point is in range 0-0x10FFFF which requires more then two bytes. – Artyom Jun 30 '10 at 07:44

1 Answers1

3

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
  • 219,715
  • 46
  • 258
  • 445