将txt文章按要求读进计算机解决方案

将txt文章按要求读进计算机
BEIJING - China will face a water supply deficit of up to 201 billion cubic meters in the next two decades if the country does not adopt proper water-saving technologies and practices, a report by global management consulting firm McKinsey & Company has found.

Given the drastic growth in industrial and municipal water use, China's total water demand could reach 818 billion cu m by 2030, but the supply would stay at only 619 billion cu m, the report estimates.

But the country has enough solutions to close the gap, and most of them are affordable and profitable, said Martin Joerss, a partner at McKinsey & Company who led the study.

The report identifies 55 solutions to boost water supply and conserve consumption in agricultural, industrial and municipal sectors.

上面是txt文档的内容。我的想法是将其读入一个这样定义的map:map<string,vector<int> >,前面存单词,后面存该单词出现在文中的所有位置的集合。单词要将大写转为小写再存,例如BEIJING读进去是beijing;vector存该单词出现在文中的位置,beijing只出现一次,相应的vector为<1>,china的位置有两个,相应向量是<2,n>等,……,标点符号忽略不读。

我也在写着,主要是不清楚怎样将一行中的单词分开成一个一个的以及如何换行,大家帮忙一块看看。


------解决方案--------------------
C/C++ code



int main()
{
    string line, str;
    ifstream fin("test.txt");  // 测试文件,

    
    string::size_type index, preindex;
    while(!fin.eof())
    {
        getline(fin, line);
        cout<<line<<endl;   // 读取文件, 显示
        
        preindex=0;
        index = line.find("#", 0);  // 寻找分割字符
        while(index<line.length() && string::npos != index)
        {
            str = line.substr(preindex, index- preindex);  //获取子串
            cout<<str<<endl;    //输出
            index++;
            preindex = index; 
            index = line.find(" ", index);  // 下一次循环,继续寻找
        }
    }
    system("pause");
    return 0;
}

------解决方案--------------------
如果只为能读出来 并且做出来
我可以提供一种方法,就是用 fstream.h头文件中的 ifstream打开文件 然后用file.get(doc)一个一个的取 然后定义一个string str=“”;如果不是空格str+=doc 遇到空格做判定处理.... 用这个扫描方式下去 绝对能做出来 但是可能效率不是很高
------解决方案--------------------
一个一个单词分开,遇到空格就是一个单词了,然后一string存进map去
------解决方案--------------------
C++ primer 的例子,跟你的需求类似,你可以参考这里的写法

C/C++ code
 

textQuery.h

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>

using namespace std;

class TextQuery
{
public:
  typedef vector < string >::size_type line_no;
  typedef map <string,set <line_no> >::iterator map_word_iterator;
  void read_file(ifstream &is)
  {
    store_file(is);
    build_map();
  }
  set <line_no> run_query(const string &) const;
  string text_line(line_no) const;
private:
  void store_file(ifstream &);
  void build_map();
  vector <string> lines_of_text;
  map <string,set <line_no> > word_map;
};


textQuery.cpp

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <string>

#include "textQuery.h"

using namespace std;

void TextQuery::store_file(ifstream &is)
{
  string textline;
  while (getline(is, textline))
    lines_of_text.push_back(textline);
}

void TextQuery::build_map()