小代码整理


整理一些小的方法代码,以后方便复用

文件读写方法:

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值