阅读std::wstring VS std::string后,我的印象是,对于Linux,我不需要担心使用该语言的任何宽字符设施 .
*类似于:std :: wifstream,std :: wofstream,std :: wstring,whar_t等 .
当我只使用std :: strings作为非ascii字符时,这似乎很好,但是当我使用字符来处理它们时却没有 .
例如:我有一个只带有unicode复选标记的文件 .
我可以读入它,将其打印到终端,然后将其输出到文件中 .
// ✓ reads in unicode to string
// ✓ outputs unicode to terminal
// ✓ outputs unicode back to the file
#include <iostream>
#include <string>
#include <fstream>
int main(){
std::ifstream in("in.txt");
std::ofstream out("out.txt");
std::string checkmark;
std::getline(in,checkmark); //size of string is actually 3 even though it just has 1 unicode character
std::cout << checkmark << std::endl;
out << checkmark;
}
但是,如果我使用char代替std :: string,则相同的程序不起作用:
// ✕ only partially reads in unicode to char
// ✕ does not output unicode to terminal
// ✕ does not output unicode back to the file
#include <iostream>
#include <string>
#include <fstream>
int main(){
std::ifstream in("in.txt");
std::ofstream out("out.txt");
char checkmark;
checkmark = in.get();
std::cout << checkmark << std::endl;
out << checkmark;
}
终端中没有任何内容(除了换行符) .
输出文件包含 â
而不是复选标记字符 .
由于char只有一个字节,我可以尝试使用whar_t,但它仍然不起作用:
// ✕ only partially reads in unicode to char
// ✕ does not output unicode to terminal
// ✕ does not output unicode back to the file
#include <iostream>
#include <string>
#include <fstream>
int main(){
std::wifstream in("in.txt");
std::wofstream out("out.txt");
wchar_t checkmark;
checkmark = in.get();
std::wcout << checkmark << std::endl;
out << checkmark;
}
我还阅读了有关设置以下语言环境的内容,但它似乎没有任何区别 .
setlocale(LC_ALL, "");
1 回答
在std :: string的情况下,你读了一行,在我们的例子中包含一个多字节的Unicode字符 . 在char情况下,您读取一个字节,甚至不是一个完整的字符 .
编辑:对于UTF-8,您应该读入一个char数组 . 或者只是std :: string,因为那已经有效了 .