C++ 如何初始化和打印 std::wstring?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8788057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:07:08  来源:igfitidea点击:

How to initialize and print a std::wstring?

c++c++-cliwstring

提问by Roee Gavirel

I had the code:

我有代码:

std::string st = "SomeText";
...
std::cout << st;

and that worked fine. But now my team wants to move to wstring. So I tried:

效果很好。但现在我的团队想搬到wstring. 所以我试过:

std::wstring st = "SomeText";
...
std::cout << st;

but this gave me a compilation error:

但这给了我一个编译错误:

Error 1 error C2664: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'const char [8]' to 'const std::basic_string<_Elem,_Traits,_Ax> &' D:...\TestModule1.cpp 28 1 TestModule1

错误 1 ​​错误 C2664:“std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)”:无法将参数 1 从“const char [8]”转换为'const std::basic_string<_Elem,_Traits,_Ax> &' D:...\TestModule1.cpp 28 1 TestModule1

After searching the web I read that I should define it as:

在网上搜索后,我读到我应该将其定义为:

std::wstring st = L"SomeText"; // Notice the "L"
...
std::cout << st;

this compiled but prints "0000000000012342"instead of "SomeText".

这编译但打印"0000000000012342"而不是"SomeText".

What am I doing wrong ?

我究竟做错了什么 ?

回答by Bo Persson

To display a wstring you also need a wide version of cout - wcout.

要显示 wstring,您还需要一个宽版本的 cout - wcout。

std::wstring st = L"SomeText";
...
std::wcout << st; 

回答by hmjd

Use std::wcoutinstead of std::cout.

使用std::wcout代替std::cout

回答by Val

This answer apply to "C++/CLI" tag, and related Windows C++ console.

此答案适用于“C++/CLI”标签和相关的 Windows C++ 控制台。

If you got multi-bytes characters in std::wstring, two more things need to be done to make it work:

如果在 std::wstring 中有多字节字符,则还需要做两件事才能使其工作:

  1. Include headers
    #include <io.h>
    #include <fcntl.h>
  2. Set stdout mode
    _setmode(_fileno(stdout), _O_U16TEXT)
  1. 包括标题
    #include <io.h>
    #include <fcntl.h>
  2. 设置标准输出模式
    _setmode(_fileno(stdout), _O_U16TEXT)

Result: Multi-bytes console

结果: 多字节控制台

回答by Hemant Metalia

try to use use std::wcout<<stit will fix your problem.

尝试使用使用 std::wcout<<st它会解决你的问题。

std::wstring st = "SomeText";
...
std::wcout << st;