C++ reads the reasons and solutions of Chinese characters garbled in text files

C++ reads the reasons and solutions of Chinese characters garbled in text files

This article introduces the reasons and solutions for the garbled Chinese characters in the text file read by C++ in the Simplified Chinese Windows operating system.

Description of the problem, C++ reads the garbled Chinese characters in the text file, the following code can read the content in d:/data.txt and output:

//C++将文本文件按行读入
#include<fstream>
#include<iostream>
#include<string>
using namespace std;

int main()
{
	ifstream file;
	file.open("d:/data.txt", ios::in);
	string s;
	while(getline(file,s))
	{
		cout<<s<<endl;
	}
	file.close();
	return 0;
}

Compile and run, if the data.txt file contains garbled characters in Chinese, see the figure below:

what reason?

To view the current encoding method of cmd, press the win+R key combination, open the run box and enter cmd to open, then right click on the cmd title bar → properties, and click to view the current encoding method:

Note the "Current Code Page" section, the current encoding is "ANSI"

Use notepad to open your text file, please pay attention to the "encoding" format of the file

The default encoding format of the text file, such as UTF-8 format, is inconsistent with the cmd encoding format "ANSI", just change the encoding format of the text file to the format "ANSI", see the figure below:

Run it again, the output is no longer garbled.

To sum up, the reason for the garbled characters in the c++ read file is that the encoding format of the text file is inconsistent with the encoding method of cmd. Modify the encoding format of the text file, and the encoding format of the text file is consistent with the encoding method of cmd.

Guess you like

Origin blog.csdn.net/cnds123/article/details/131062643