c++读取中文字符

jiangxiaoma111 jiangxiaoma111 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我现在想从一个文本中读取其中的字符,然后找到想要的文本,把它给替换掉。但是读取中文的字符的时候不能成功,总是乱码。我在网上找到的都没有,现在读取的时候,把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;
}
...全文

相关推荐

评论 24
收藏 已收藏
分享
返回顶部
jiangxiaoma111
C++ 语言 65,214 成员 250,514 内容