c++读取中文字符
我现在想从一个文本中读取其中的字符,然后找到想要的文本,把它给替换掉。但是读取中文的字符的时候不能成功,总是乱码。我在网上找到的都没有,现在读取的时候,把ifstream换成wifstream,但是打开文件的时候出错。
下面的是代码
求指点。。
下面的是代码
求指点。。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//subs1是要查找的字符串
//subs2 是要将subs1从text中替换掉的字符串
void replace(wstring &text, const wstring &subs1, const wstring &subs2)
{
wcout<<subs1<<" "<<subs1.size()<<endl;
wcout<<subs2<<" "<<subs2.size()<<endl;
wstring::size_type beg = text.find(subs1);
cout<<beg<<endl;
if(beg >= text.size())
{
cout<<"不能匹配"<<endl;
return;
}
text.erase(beg, subs1.size());
text.insert(beg, subs2);
/*while(beg < text.size())
{
beg = text.find(subs1);
text.erase(beg, subs1.size());
text.insert(beg, subs2);
}*/
}
//从file中读取文本,然后将str给初始化。
void init(wifstream &is, const string &file, wstring &str)
{
is.close();
is.clear();
is.open(file.c_str());
str = L"";
if(!is)
{
cerr<<"Cannot open the file : "<<file<<endl;
return;
}
wstring line;
locale china("chs");
wcout.imbue(china);
while(getline(is,line))
{
str = str + line + L"\n";
wcout << str << endl;
}
//string s = str.rfind("\n");
str.erase(str.rfind(L"\n"), str.size());
}
//将替换好的text再重新输出到一个文件中
void output_file(wofstream &os, const string &out_file, const wstring &str)
{
os.close();
os.clear();
os.open(out_file.c_str());
if(!os)
{
cerr<<"Cannot output the string to the file : "<<out_file<<endl;
}
os<<str<<endl;
os.close();
}
int main()
{
//file path F:\\sb\\sb3\\www.bill-jc.com\\test.html
string in_file = "F:\\test3.txt";
string out_file = "f:\\test.html";
string str1_file = "f:\\test1.txt";
string str2_file = "f:\\test2.txt";
//variable
locale china("chs");
wstring text, str1, str2;
wifstream is;
wofstream os;
is.imbue(china);
os.imbue(china);
init(is, in_file, text);
while(true)
{
init(is, str1_file, str1);
init(is, str2_file, str2);
replace(text, str1, str2);
cout<<"Y/N"<<endl;
char i;
cin>>i;
if(i == 'N')
break;
}
//output_file(os, out_file, text);
return 0;
}
...全文
相关推荐
检查xml和cpp文件中中文字符
写的用来找xml和cpp等文件中出现中文字的文件和位置,挺实用的,只传了cppwenjian
BasicExcelSample.zip
支持中文的EXCEL处理,有好多的人在找这段代码,所有先放这让大家共享下载吧!
zip库(解决文件名中文乱码问题).zip
从其他网站上下载的库,修改了字符串编码转换的方法,解决中文乱码问题,使用示例可见https://blog.csdn.net/qq_28742901/article/details/116156457
IFELanguageDemo.src_VC++源码_
VC simple Chinese characters conversion pinyin small programs
C++ JSON库使用指南[可运行源码]
本文详细介绍了如何在C++项目中使用jsoncpp库进行JSON文件的读写操作。首先提供了jsoncpp的下载地址和编译方法,包括如何通过运行amalgamate.py生成所需的.h和.cpp文件。接着,文章展示了如何包含必要的头文件,并提供了多个实用的代码示例,包括普通文件读写、JSON文件读写以及从字符串创建JSON对象的方法。特别强调了处理UTF-8中文字符时可能出现的乱码问题,并给出了解决方案,即在创建JSON读写工厂对象时设置emitUTF8属性为true。此外,文章还介绍了JSON对象的两种使用方法:通过get方法和直接通过键名访问。最后,作者提到了一些已知的小bug,并提供了进一步学习的参考链接。


