开发者

How to cast wchar_t into int for displaying the code point?

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜