当我想用Unicode弄乱并使用它时,我的程序中有一个简单的功能。在此功能中,我希望显示用户输入的字符的代码值。似乎有可能,这是我的功能:

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

现在,如您所见,我只是想显示整数值(例如ASCII字符,例如 (int) "a"),但是类似 listcode(L"&") 将显示为 &: & !

难道找不到这样的广泛字符的整数值吗?

有帮助吗?

解决方案

在C ++中,您不能在字符串和其他字符串中添加任何内容。没有隐含的转换 int (或其他任何)要串。这就是字符串类型的设计方式。
相反,您要做的是使用字符串流:

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

但是,在实践中,当在C ++中转换为字符串时,最好将函数写入流比返回字符串:

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

这样,如果您想将某些内容输出到控制台或文件,则可以直接通过 std::cout 或文件流,如果您想要一个字符串,则只需传递字符串流即可。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top