- #pragma warning(disable:4786)
- #include <string>
- #include <iostream>
- #include <fstream>
- #include <vector>
- using namespace std;
- typedef pair<short,short> location;
- typedef vector<location> loc;
- typedef vector<string> text;
- typedef pair<text*,loc*> text_loc;
- // 返回值是指向string vector 的指针
- text*
- retrieve_text()
- {
- string file_name;
- cout << "please enter file name: ";
- cin >> file_name;
- // 打开文本文件以便输入 ...
- ifstream infile( file_name.c_str(), ios::in );
- if ( ! infile )
- {
- cerr << "oops! unable to open file "
- << file_name << " -- bailing out!/n";
- exit( -1 );
- }
- else cout << '/n';
- text *lines_of_text = new text;
- string textline;
- typedef pair<string::size_type, int> stats;
- stats maxline;
- int linenum = 0;
- while ( getline( infile, textline, '/n' ))
- {
- cout << "line read: " << textline << '/n';
- if ( maxline.first < textline.size() )
- {
- maxline.first = textline.size();
- maxline.second = linenum;
- }
- lines_of_text->push_back( textline );
- linenum++;
- }
- cout<<"The max_line size is "<<maxline.first<<";"<<endl;
- cout<<"The max_line_num is "<<maxline.second<<";"<<endl;
- return lines_of_text;
- }
- text_loc*
- separate_words( const text *text_file )
- {
- // words: 包含独立单词的集合
- // locations: 包含相关的行/列信息
- vector<string> *words = new vector<string>;
- vector<location> *locations = new vector<location>;
- short line_pos = 0; // current line number
- // iterate through each line of text
- for ( ; line_pos < text_file->size(); ++line_pos )
- {
- // textline: 待处理的当前文本行
- // word_pos: 文本行中的当前列位置
- short word_pos = 0;
- string textline = (*text_file)[ line_pos ];
- string::size_type pos = 0, prev_pos = 0;
- while (( pos = textline.find_first_of( ' ', pos ))
- != string::npos )
- {
- // 存储当前单词子串的拷贝
- words->push_back(
- textline.substr( prev_pos, pos - prev_pos ));
- // 将行/列信息存储为pair
- locations ->push_back(
- make_pair( line_pos, word_pos ));
- // 为下一次迭代修改位置信息
- prev_pos = ++pos;
- word_pos = pos;
- }
- // 现在处理最后一个单词
- words->push_back(
- textline.substr( prev_pos, pos - prev_pos ));
- locations->push_back(
- make_pair( line_pos, word_pos ));
- }
- return new text_loc( words, locations );
- }
- void main()
- {
- text* txt_file = retrieve_text();
- text_loc* txt_loc_map = separate_words(txt_file);
- text::iterator iter = (txt_loc_map->first)->begin();
- loc::iterator iter2 = (txt_loc_map->second)->begin();
- for(;iter != (txt_loc_map->first)->end(); iter++,iter2++)
- {
- cout<<*iter<<" ("<<iter2->first<<","<<iter2->second<<");"<<endl;
- }
- }
C++Primer6.8节可执行console程序代码
最新推荐文章于 2024-07-12 16:34:36 发布