我最近遇到了字符串文字,并发现了一些新的字符串类型,比如u16string和u32string。我发现可以使用std::wcout将wstring打印到控制台,但对于u16string或u32string则不起作用。如何将它们打印到控制台?
我最近遇到了字符串文字,并发现了一些新的字符串类型,比如u16string和u32string。我发现可以使用std::wcout将wstring打印到控制台,但对于u16string或u32string则不起作用。如何将它们打印到控制台?
我猜下面的代码应该可以工作,但请注意,在c++17中<codecvt>
已被弃用。
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main() {
std::u16string str = u"sample";
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
std::cout << converter.to_bytes(str) << std::endl;
return 0;
}
#include <string>
#include <iostream>
int main() {
std::u16string str(u"abcdefg");
for (const auto& c: str)
std::cout << static_cast<char>(c);
}
不确定后者的稳健性以及您需要它有多高的效率。
@Burgers的解决方案适用于clang 12.0.0(macOS Catalina XCode)。
请注意,对于u32string,您需要使用char32_t。
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main() {
using namespace std;
u32string str = u"很有用"; // btw. str.size() == 4
wstring_convert<codecvt_utf8<char32_t>, char32_t> converter;
cout << converter.to_bytes(str) << endl;
return 0;
}