'How to initialize and print a std::wstring?
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:
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
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"
.
What am I doing wrong ?
Solution 1:[1]
To display a wstring you also need a wide version of cout - wcout.
std::wstring st = L"SomeText";
...
std::wcout << st;
Solution 2:[2]
Use std::wcout
instead of std::cout
.
Solution 3:[3]
This answer apply to "C++/CLI" tag, and related Windows C++ console.
If you got multi-bytes characters in std::wstring, two more things need to be done to make it work:
- Include headers
#include <io.h>
#include <fcntl.h>
- Set stdout mode
_setmode(_fileno(stdout), _O_U16TEXT)
Solution 4:[4]
try to use use std::wcout<<st
it will fix your problem.
std::wstring st = "SomeText";
...
std::wcout << st;
Solution 5:[5]
Another way to print wide string:
std::wstring str1 = L"SomeText";
std::wstring strr2(L"OtherText!");
printf("Wide String1- %ls \n", str1.c_str());
wprintf(L"Wide String2- %s \n", str2.c_str());
- For printf: %s is narrow char string and %ls is wide char string.
- For wprintf: %hs is narrow char string and %s is wide char string.
Solution 6:[6]
In addition to what is said above, there are octal and hexadecimal character encodings
std::wstring blankHex = L"\x0020";
std::wstring blankOct= L"\040";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bo Persson |
Solution 2 | hmjd |
Solution 3 | |
Solution 4 | Hemant Metalia |
Solution 5 | Nikita Jain |
Solution 6 | Sam Ginrich |