问题

在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编译也可以正常显示中文。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐