您的位置:首页 > 编程语言 > C语言/C++

C++读取文件中的汉字,wifstream,wstring的使用

2017-04-05 21:42 495 查看
最近的项目需要在图片上写汉字,用了opencv,freetype来实现,但是在Linux下开发遇到了很多的问题,尤其是Puttext函数写连续的汉字时会出现乱码的情况,也是把我折磨的够惨,特此记录。

为啥要用wifstream呢?因为文件中是汉字,占双字节,如果只用ifstream读取的话,在PutText(const char*)这个函数的时候,汉字是不能正常显示的,因此只能用PutText(const wchar_t* ) 这个函数了,也是通过大量的试验去试各种方法,最终解决了乱码问题。

言归正传,直接看怎么读取文件中的汉字吧,并用wstring来表示,可以有wstring.data()来得到const wchar_t* 类型的。

#include<locale>
#include<iostream>
#include<string>
#include<fstream>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <math.h>
#include <opencv/cv.h>
#include <stdio.h>
#include "normal.h"
#include <time.h>

#include "lib/CvxText.h"
#include <freetype2/ft2build.h>

using namespace std;

int main(){

//读取图片,是在图片上写汉字的功能
Mat src = imread("drivelic
4000
ense1.jpg");
if(src.data == NULL){
cout<<"read image error"<<endl;
return 0;
}

Mat src1 = src.clone();
CvxText chinese_text("/font/aa.ttf");
CvScalar fsize = cvScalar(38,0.05,0.15,0);
float p = 0.6;
chinese_text.setFont(NULL,&fsize,NULL,&p);
CvScalar color = CV_RGB(0,0,0);
IplImage ipl(src1);

//一定要写哦,不写会报错
locale china("zh_CN.UTF-8");
wifstream infile;

//读取文件,如果只要读取文件的功能,上面的那部分可以忽略
infile.open("../meta/roads_line.txt");
if(!infile.is_open()){
cout<<"fail to open the file"<<endl;
return 0;
}

infile.imbue(china);
int i=0;
wstring value;
while(!infile.eof()){
infile >> value;  //这就是读取到的汉字,用wstring存储

//opencv中往图片上写汉字     chinese_text.putText(&ipl,value.data(),cvPoint(30*i,45*i),color);

char coor[256];
sprintf(coor,"%d",i);
imwrite("meta/desimage"+string(coor)+".jpg",src1);
wcout<<value<<endl; //可以打印出来看看value的值
}

if (infile.eof()) {
cout<<"End of file reached!"<<endl;
}
else if (infile.fail()){
cout<<"Input terminated by data mismatched!"<<endl;
}
else{
cout<<"Input terminated for unknown reason!"<<endl;
}

infile.close();
return 0;
}


#精简后只读取文件的代码
#include<locale>
#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main(){

//一定要写哦,不写会报错
locale china("zh_CN.UTF-8");
wifstream infile;

//读取文件,如果只要读取文件的功能,上面的那部分可以忽略
infile.open("../meta/roads_line.txt");
if(!infile.is_open()){
cout<<"fail to open the file"<<endl;
return 0;
}

infile.imbue(china);
wstring value;
while(!infile.eof()){
infile >> value;  //这就是读取到的汉字,用wstring存储
wcout<<value<<endl; //可以打印出来看看value的值
}

if (infile.eof()) {
cout<<"End of file reached!"<<endl;
}
else if (infile.fail()){
cout<<"Input terminated by data mismatched!"<<endl;
}
else{
cout<<"Input terminated for unknown reason!"<<endl;
}

infile.close();
return 0;
}


代码跑通后感觉很简单,但是网上相关wstring 的资料非常少,找了好久,试了很久才达到预期的功能,记录下来,希望以后用到的时候方便查阅。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息