我正在尝试遍历一个UTF-8字符串。据我所知,问题在于UTF-8字符具有可变长度,因此我不能只按照字符逐个遍历,而必须使用某种转换方法。我相信现代C++中有一个可以解决这个问题的函数,但我不知道它是什么。
#include <iostream>
#include <string>
int main()
{
std::string text = u8"řabcdě";
std::cout << text << std::endl; // Prints fine
std::cout << "First letter is: " << text.at(0) << text.at(1) << std::endl; // Again fine. So 'ř' is a 2 byte letter?
for(auto it = text.begin(); it < text.end(); it++)
{
// Obviously wrong. Outputs only ascii part of the text (a, b, c, d) correctly
std::cout << "Iterating: " << *it << std::endl;
}
}
使用clang++ -std=c++11 -stdlib=libc++ test.cpp
编译。
根据我的阅读,不应使用wchar_t
和wstring
。