【GCC】解决GCC编译运行的代码在VScode中显示中文乱码

文章讲述了在VScode中使用C++插件编译运行代码时,由于UTF-8源文件和Windows终端默认的GBK编码冲突导致中文显示乱码,通过添加-fexec-charset=GBK选项或修改源文件编码解决此问题。
摘要由CSDN通过智能技术生成

问题

在VScode中,使用C/C++插件,在终端中调用gcc编译运行cpp代码,示例代码如下:

// utf-8
#include<iostream>
using namespace std;

class Student
{
public:
    // 成员变量
    char *name;
    int age;
    float score;
    // 成员函数
    void say()
    {
        cout << name << "的年龄是" << age << ",成绩是" << score << endl;
    }
};

int main()
{
    Student stud1;
    stud1.age = 12;
    stud1.name = "djsakl";
    stud1.score = 90;

    stud1.say();
}

当按照如下所示编译运行示例代码,结果如下

PS D:\code\cpp> g++ .\test.cpp -o test
.\test.cpp: In function 'int main()':
.\test.cpp:22:18: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   22 |     stud1.name = "djsakl";
      |                  ^~~~~~~~
PS D:\code\cpp> .\test.exe
djsakl鐨勫勾榫勬槸12锛屾垚缁╂槸90

可以看到运行结果中文显示乱码。

解决方法

PS D:\code\cpp> g++ -fexec-charset=GBK .\test.cpp -o test2
.\test.cpp: In function 'int main()':
.\test.cpp:22:18: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   22 |     stud1.name = "djsakl";
      |                  ^~~~~~~~
PS D:\code\cpp> .\test2.exe
djsakl的年龄是12,成绩是90

当在g++编译时加入选项-fexec-charset=GBK可以看到正确显示中文。
因为源文件是utf-8编码,而windows终端默认采用cp936,其中中文对应GBK,所以显示乱码。当加入选项-fexec-charset=GBK后将正确显示。
或者将源文件改为GBK编码格式后使用g++ .\test.cpp -o test编译也可以正常显示中文。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值