整理一些小的方法代码,以后方便复用
文件读写方法:
1. 将文件中的句子读到vector中,每行一句
vector<string> FileIOfunc::getAllSentenceFromFile(string filePath){
ifstream infile;
string line;
vector<string> allSentence;//保存所有的句子
infile.open(filePath);//打开文件
if(!infile){
cerr<<"error:unable to open input file: "<<infile<<endl;
}
while(getline(infile,line)){
allSentence.push_back(line);
}
infile.clear();
infile.close();
cout<<"读文件"<<filePath<<"结束,文件行数为:"<<allSentence.size()<<endl;
return allSentence;
}
2. 把所有的句子保存回文件
void FileIOfunc::saveAllSentenceToFile(string filepath,vector<string> resultSentence){
ofstream outfile;
//outfile.open(filepath,ios::app);//以追加方式写文件
outfile.open(filepath);//以覆盖方式写文件
//把所有的句子保存到文件
for(int i=0;i<resultSentence.size();i++)
{
outfile<<resultSentence[i]<<"\r\n";//先回车后换行,顺序不能换,转意符是反斜杠
}
cout<<"所有的句子保存回文件完成"<<endl;
outfile.clear();
outfile.close();
}
3. 读文件,每次读一个字符进来,每次读一个词进来(以空格分隔)
ifstream infile;
char a;
string line;
string word;
infile.open(filepath);//打开文件
if(!infile){
cerr<<"error:unable to open input file: "<<infile<<endl;
}
//每次读取一个字符进行处理
do{
infile.get(a);
if(infile.eof())
break;
cout<<a;
getchar();
}while(!infile.eof());
//每次读取一行进行处理,行与行之间以回车换行分隔
while(getline(infile,line)){
allSentence.push_back(line);//每一行都保存到vector中
//cout<<line;
}
cout<<"文件读取完毕"<<endl;
cout<<"vector长度"<<allSentence.size()<<endl;
//每次读一个词进行处理,词和词之间用空格分开
while( infile>>word ){
//cout << "Read from file: "<< word<< endl;
wordCount++;
lexicalItem.insert(word);
if(word.size()>maxLength){
maxLength = word.size();
cout<<"迄今为止,最长的词"<<word<<",长度为:"<<word.size()/2<<endl;
}
//getchar();
}
maxLength = maxLength;
infile.close();
4.