Solve the problem of Chinese garbled characters in the input stream of C/C++ fscanf function ifstream

When the fscanf function is used in the C language, garbled characters may appear when introducing Chinese. This article is used to explain the cause of the problem and provide a solution.

problem demo

insert image description here
As shown in the figure above, we read a line of information from the file pointer fp of data.txt into the program and print it on the display. The result is as follows: You can
insert image description here
see that the Chinese part is garbled. If you don’t believe me, try replacing the Chinese with English, and it will be normal. Now, I can guess that it is a character encoding problem; (C++'s ifstream also has the same problem)

The garbled characters are caused by the incompatibility between the txt file itself (utf-8 encoding) and the compiler we use such as Dev-C++ or VS2019. Just set the file format to make it compatible with the compiler;

Solution

Open the data.txt file just now, click File->Save As->Encoding in the upper left corner and set ANSI
(be careful not to change the file name and path randomly, otherwise the program cannot be found and cannot be opened)
insert image description here

Guess you like

Origin blog.csdn.net/wtl666_6/article/details/129226659