C++ cout输出中文信息乱码问题解决

本文讲述了在C++中实例化学生类时遇到的汉字乱码问题,通过推荐的方法一是修改注册表设置,取消run.processes.with.pty选项;另一种方法是使用Windows API SetConsoleOutputCP函数将输出编码设为CP_UTF8。详细代码示例和解决步骤提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 问题描述:在实例化学生类对象时,对学生的姓名采用了形如“张三”这样的汉字信息,在输出学生姓名时出现了乱码问题(如下图):

 解决办法:

方法一(推荐,一劳永逸):

1.同时按住Ctrl+Alt+Shift+/四个键,选择注册表

2.取消勾选run.processes.with.pty,点击关闭,大功告成!

方法二:

采用<windows.h>头文件中的SetConsoleOutputCP(CP_UTF8)函数来设置在显示器打印时的编码格式就解决了乱码问题。

完整代码如下:

#include <iostream>
#include <windows.h>

using namespace std;

class Student {
public:
    string name;
    int num;

    Student(const string &name, int num) : name(name), num(num) {}

    friend ostream &operator<<(ostream &os, const Student &student) {
        os << "name: " << student.name << " num: " << student.num;
        return os;
    }
};

int main() {
    SetConsoleOutputCP(CP_UTF8);
    Student s("张三", 1001);
    cout << s << endl;
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值