C++打印中文

来源:互联网 发布:c语言for语句continue 编辑:程序博客网 时间:2024/06/07 03:23

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 0
原创粉丝点击