问题
在VS Code中读取.txt文件,并将读取到的内容传输到cout中进行显示,命令窗口中显示的汉字乱码。但输入输出文件没有乱码。
代码
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
//#include <stdlib.h>
using namespace std;
int main()
{
vector<string> words;
string word;
// 读取文件
ifstream infile;
string str;
str = "/Users/Administrator/Desktop/essential C++/cpp_source/chapter_1/1_7.txt";
infile.open( str );
if ( ! infile )
{
cout << "Sorry, file wasn't read. ";
}
else
{
while ( infile >> word )
{
words.push_back( word );
}
}
// cout显示
for (int i = 0; i < words.size(); i++)
{
cout << words[ i ];
}
//system( "pause" );
// 文字排序
sort( words.begin(), words.end());
// 写入另一个文件
ofstream outfile( "1_7_out.txt" );
for (int i = 0; i < words.size(); i++)
{
outfile << words[ i ];
}
return 0;
}
输出结果
曾尝试修改tasks.json文件中的设置,代码如下:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++.exe build active file",
"command": "C:\\TDM-GCC-64\\bin\\g++.exe",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "new",
"showReuseMessage": true,
"clear": false
},
"args": [
"-g",
// 处理mingw中文编码问题
"-fexec-charset=GBK", // 令mingw按GBK编码生成exe文件
"-finput-charset=UTF-8",// 令mingw按UTF-8编码处理(此参数可以不设置)
//
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "test",
"isDefault": true
}
}
]
}