一、简单使用C++文件流方法实现文本读取,并且简单统计最长字符串
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <memory>
using namespace std;
typedef pair<string::size_type,int> stats;
typedef pair<vector <string>*,stats*> return_stats;
return_stats * Retrieve_Text();
return_stats * Retrieve_Text()
{
string file_name;
cout<<"请输入文件名字:";
cin>>file_name;
ifstream infile(file_name.c_str(),ios::in);
if(!infile)
{
cerr<<"infile"<<endl;
exit(-1);
}
else
{
cout<<endl;
}
vector <string> * lines_of_text = new vector <string>;
string textline;
stats * maxline = new stats;;
int linenum=0;
while(getline(infile,textline,'\n'))
{
cout<<"line read:"<<textline<<endl;
if(maxline->first < textline.size())
{
maxline->first = textline.size();
maxline->second = linenum;
}
linenum++;
lines_of_text->push_back(textline);
}
return new return_stats (lines_of_text,maxline);
}
运行结果:
请输入文件名字:dante.txt
line read:fahgfagfgdks
line read:发噶开个房返回咖啡
line read:fksfksa发生的回复gfkgafkagfkagfkagfjasgfjasgajhgaje
最长字符个数:56最长字符行号:2
二、拆份每行的单词
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <memory>
using namespace std;
typedef pair<string::size_type,int> stats;
typedef pair<vector <string>*,stats*> return_stats;
int Separate_Words(return_stats * text_inf_or_data);
int Separate_Words(return_stats * text_inf_or_data)
{
vector <string>::iterator text_string_p = text_inf_or_data->first->begin();
vector <string> words;
int line_num=0;
for(; text_string_p < text_inf_or_data->first->end(); text_string_p++)
{
int pos = 0;
int word_pos = 0;
string text_line = * text_string_p;
cout<<"行数据:"<<text_line<<endl;
while((pos = text_line.find_first_of(' ',pos)) != string::npos)
{
words.push_back(text_line.substr(word_pos,pos-word_pos));
cout<<"line:"<<line_num<<" pos:"<<pos<<" word:"<<text_line.substr(word_pos,pos-word_pos)<<endl;
word_pos = ++pos;
}
words.push_back(text_line.substr(word_pos,text_line.size()-word_pos));
cout<<"line:"<<line_num<<" pos:"<<word_pos<<" word:"<<text_line.substr(word_pos,text_line.size()-word_pos)<<endl;
line_num++;
cout<<endl;
}
return 0;
}
运行结果:
输入文件名字:dante.txt
line read:fahgfa gfgdks
line read:发噶开个 房返回 咖啡
line read:fksfksa发生 的回复gfkgafkag fkagfkagfjasgfj asgajhgaje
最长字符个数:59 最长字符行号:2
行数据:fahgfa gfgdks
line:0 pos:6 word:fahgfa
line:0 pos:7 word:gfgdks
行数据:发噶开个 房返回 咖啡
line:1 pos:12 word:发噶开个
line:1 pos:22 word:房返回
line:1 pos:23 word:咖啡
行数据:fksfksa发生 的回复gfkgafkag fkagfkagfjasgfj asgajhgaje
line:2 pos:13 word:fksfksa发生
line:2 pos:32 word:的回复gfkgafkag
line:2 pos:48 word:fkagfkagfjasgfj
line:2 pos:49 word:asgajhgaje
main函数:
int main()
{
return_stats * text_inf_or_data = Retrieve_Text();
cout<<endl<<"最长字符个数:"<<text_inf_or_data->second->first << " 最长字符行号:"<< text_inf_or_data->second->second<<endl<<endl;
Separate_Words(text_inf_or_data);
return 0;
}