CLion中编写C/C++代码运行cout输出中文乱码-多种解决方法

问题案例:

#include <iostream>

using namespace std;

int main() {
    std::cout << "Hello, World!" << std::endl;
    cout << "I 喜欢 c++" << endl;
    cout << "I love c++" << endl;
    return 0;
}

运行结果:

解决方法:

方法1.引入windows.h库。main函数里加上设置控制台输出编码。

示例代码:

#include <iostream>
#include "windows.h"
using namespace std;

int main() {
    SetConsoleOutputCP(CP_UTF8);
    std::cout << "Hello, World!" << std::endl;
    cout << "I 喜欢 c++" << endl;
    cout << "I love c++" << endl;
    return 0;
}

结果 :

方式2:main函数加上system("chcp 65001");

示例代码:

#include <iostream>
//#include "windows.h"
using namespace std;

int main() {
//    SetConsoleOutputCP(CP_UTF8);
    system("chcp 65001");
    std::cout << "Hello, World!" << std::endl;
    cout << "I 喜欢 c++" << endl;
    cout << "I love c++" << endl;
    return 0;
}

输出结果:  会多一行

以上方法都不完美,代码里都会加东西,甚至影响输出结果。

完美方法3:改为GBK格式

右下角点击utf-8,改为GBK格式,并点击转换即可。

猜你喜欢

转载自blog.csdn.net/A2902/article/details/141184271