[英]std::string is natively encoded in UTF-8 but char can not hold utf characters?
在閱讀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;
}
同樣的程序不工作,但是,如果我在的地方的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, "");
在std :: string的情況下,你讀了一行,在我們的例子中包含一個多字節的Unicode字符。 在char情況下,您讀取一個字節,甚至不是一個完整的字符。
編輯:對於UTF-8,您應該讀入一個char數組。 或者只是std :: string,因為那已經有效了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.