C++ 讀中文 C++ read write Traditoinal Chinese file C++ read UTF-8 file

  • 2132
  • 0
  • c++
  • 2021-06-04

C++ 讀中文  C++ read write Traditoinal Chinese file C++ read UTF-8 file

This article use English  (Traditoinal Chinese) to write:

I spend lots of time and complete a workable code (花了滿多時間試出了可行的一段程式碼),

and reference to some stackoverflow posts,  (其中參考了幾篇 stackoverflow)

first create a txt file and write some chinese (or UTF-8) words and save with UTF-8 encoding,  (先建立一個txt檔寫一些中文存檔)

then the code below can "cout" print file content to the console,  (下方程式碼就可以印出中文字到console畫面)

#include <sstream>
#include <fstream>
#include <codecvt>

//  Thanks to 
//  https://stackoverflow.com/questions/4775437/read-unicode-utf-8-file-into-wstring
//  
std::wstring readFile(const char* filename)
{
	std::wifstream wif(filename);
	wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
	std::wstringstream wss;
	wss << wif.rdbuf();
	return wss.str();
}

 
std::wstring wstr2;
wstr2 = readFile("C:\\yourFile.txt");

wcout << wstr2;

 

Following is another way to read / print Chinese (or UTF-8 words), (下面是另一個讀中文(或UTF-8文字)的程式碼方法)

I find that if run it with visual studio console it print garbled text  #$@%@#,  (我發現用visual studio debug的console 會印出亂碼)

but if I use cmd to run it can print clearly chinese(or UTF-8 words),  (但用 cmd 直接執行程式可以正確印出中文(或UTF-8文字))

so it may depend on the encoding setting of console,  (可能和 console  的顯示編碼設定有關)

and then it write the file content to "yourFileOutput.txt", you can give the output path arbitrarily,  (然後程式碼會將檔案內容另外寫到 yourFileOutput.txt  可以自訂輸出路徑,這是證明可用C++讀一個中文(或UTF-8文字)的檔案然後寫到另一個檔案也是正確寫中文不會寫亂碼)

and open the output file I can see it write chinese(or UTF-8 words) content correctly.  (打開輸出檔可看到正確寫入中文(或UTF-8文字))

C++ Code:

#include <iostream>
#include <fstream>
#include <string>


//  Thanks to 
//  https://stackoverflow.com/questions/33806620/use-wstring-get-line-read-file
//
std::wfstream fichier("C:\\yourFile.txt");
if (fichier)
{
	std::wstring wstr;
	//  Thanks to 
	//  https://stackoverflow.com/a/18226387/4573839
	//  
	std::wofstream f(L"C:\\yourFileOutput.txt");

	while (std::getline (fichier, wstr))
	{
		std::wcout << wstr << std::endl;
		f << wstr << std::endl;
	}
	
	f.close();
}