猎猫骑巨兽 2020-10-18 16:07 采纳率: 0%
浏览 227

VS Code中,将读取的.txt文件在命令窗口中显示,汉字乱码?

问题

在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
            }
        }
    ]
}
  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-20 21:39
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分