C++打印中文

text.txt内容:
这里写图片描述

// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <direct.h>
#include<fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <windows.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    //读文件
    ifstream fin("text.txt");
    if(!fin) {
        cerr << "Error opening input stream" << endl;
    }
    char* buffer = (char*)malloc(6);
    fin.getline(buffer,6);
    fin.close();
    //打印文件中的中文多字符不需要使用setlocate指定编码
    printf("printf file string :%s\n",buffer);
    cout<<"cout file string :"<<buffer<<endl;

    //打印参数中的宽字符,输入参数为"中国人"
    wchar_t* arg = argv[1];
    wprintf(L"wprintf setlocale before: %s\n",arg);
    //把宽字符转成多字符打印,这种转换方式会多出一些乱码字符
    int len = wcslen(argv[1])*2;
    char* mbuf = (char*)malloc(len);
    wcstombs(mbuf,argv[1],len);
    printf("printf change buffer setlocale before:%s\n",mbuf);

    //无需调用setlocale也不会乱码
    int szlen = ::WideCharToMultiByte(CP_ACP, 0, argv[1], -1, NULL, 0, NULL, NULL);
    char* nbuf = new char[szlen + 1];
    ::WideCharToMultiByte(CP_ACP, 0,argv[1], -1, nbuf, szlen, NULL, NULL);
    cout<<"no need setlocale way:"<<nbuf<<endl;
    printf("printf nbuf:%s\n",nbuf);

    //必须使用setlocale指定编码,才不会乱
    setlocale(LC_ALL, "Chinese-simplified");  
    printf("printf change buffer setlocale after:%s\n",mbuf);
    wprintf(L"setlocale after %s\n",arg);
    wcout<<"wcount buffer "<<arg<<endl;
    getchar();
    return 0;
}

输出结果:
这里写图片描述

代码下载:c++打印中文字符

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值