在一个文件中读入“我有1支铅笔,但是仓库里面有353628支”,在另一个文件中写入“我有一支铅笔,但是仓库里面有三五三六二八支”,以及fstream问题
代码如下:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
bool shishuzi(string &a,int i)
{
if(a[i]>='1'&&a[i]<='9'&&a[i]<128) return 1;
else return 0;
}
void change(string &a,int i,ofstream &out)
{
if(a[i]=='1')
out<<"一";
else if(a[i]=='2')
out<<"二";
else if(a[i]=='3')
out<<"三";
else if(a[i]=='4')
out<<"四";
else if(a[i]=='5')
out<<"五";
else if(a[i]=='6')
out<<"六";
else if(a[i]=='7')
out<<"七";
else if(a[i]=='8')
out<<"八";
else if(a[i]=='9')
out<<"九";
}
int main()
{
ifstream infile("F:\\C++ project\\pen\\in.txt");
ofstream outfile("F:\\C++ project\\pen\\out.txt");
if(!infile.is_open()) cout<<"文件打开失败!"<<endl;
else
{
string buffer;
getline(infile,buffer);
//out<<buffer;
int length=buffer.length();
for(int i=0;i<=length-1;)
{
if(shishuzi(buffer,i))
{
change(buffer,i,outfile);
i++;
}
else
{
string temp;
temp.resize(2);
temp[0]=buffer[i];
temp[1]=buffer[i+1];
outfile<<temp;
i=i+2;
/*char temp[2];
temp[0]=buffer[i];temp[1]=buffer[i+1];
outfile<<temp;i=i+2;*/
}
}
}
}
错误1:生成错误,提示:无法访问 private 成员(在“std::basic_ios<_Elem,_Traits>”类中声明)
原因1:error C2248: “std::basic_ios<_Elem,_Traits>::basic_ios”: 无法访问 private 成员(在“std::basic_ios<_Elem,_Traits>”类中声明)问题解决
原因好像是流对象是不允许复制,所以在传给函数作为参数是应该传入引用,这样就没有问题了
void parse_text(string file_name,ofstream out)
改成:
void parse_text(string file_name,ofstream &out)
即ifstream
类型和ofstream
类型做参数时应使用引用。
错误2:汉字之间有空格
原因2:
string temp;
temp.resize(2);
写成了
temp.resize(4);
错误3:输出的明明是一二三等汉字,结果却是五位数字。
原因3:输出格式写成了:
if(a[i]=='1')
out<<‘一’;
......
单引号应改成双引号:
if(a[i]=='1')
out<<“一”;
......
**其它:**注意输入输出不要写反了!
错误4:
ofstream out("F:\\C++ project\\pen\\out.txt");
out << "一";
输出结果用记事本打开是“h”。
原因4:用写字板打开就是“一”;但是如果写入的是“一二”,则记事本显示正确,应该是编码的问题。