练习使用命令行调用C++函数,利用fstream流,读取输入的文件;

  1. ifstream in;

    in.open(char[]);

      in.open(string.c_str);

  通过c_str把string对象转化为C字符串,它返回一个客户程序可读不可改的指向字符数组的指针。

 

在#include之前加入#pragma warning(disable : 4786) 屏蔽4786警告;

类定义体之后记得接“;”;

in.open("text.txt")默认执行的是在cpp文件所在文件夹;

 

 查找

 1 #pragma warning(disable : 4786) //Disable warning C4786
 2 
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 #include <algorithm>
 7 #include <fstream>
 8 #include <sstream>
 9 #include <map>
10 #include <set>
11 
12 using namespace std;
13 
14 class TextQuery
15 {
16     friend int main(int argc, char * argv[]);
17 public:
18     void read_file(ifstream &in);
19     set<vector<string>::size_type> run_query(const string q);
20 private:
21     vector<string> lines_of_text;
22     map< string, set<vector<string>::size_type> > word_map;
23 };
24 
25 void TextQuery::read_file(ifstream &in)
26 {
27     string str;
28     while (getline(in, str))
29         lines_of_text.push_back(str);
30     for(vector<string>::size_type line_no=0; line_no!=lines_of_text.size(); line_no++)
31     {
32         string word;
33         istringstream sin(lines_of_text[line_no]);
34         while (sin>>word)
35         {
36             for (string::size_type s=0;word[s]!='\0';s++)
37             {
38                 while (ispunct(word[s]))
39                 {
40                     word.erase(s);
41                 }
42             }
43             word_map[word].insert(line_no);
44         }
45     }
46 }
47 
48 set<vector<string>::size_type> TextQuery::run_query(const string q)
49 {
50     map<string, set<vector<string>::size_type> >::iterator m_itr=word_map.find(q);
51     if (m_itr!=word_map.end())
52         return m_itr->second;
53     else
54         return set<vector<string>::size_type>();
55 }
56 
57 int main(int argc, char * argv[])
58 {
59     ifstream in;
60     in.close();
61     in.clear();
62     in.open("D:\\C++\\TextQuery\\Debug\\text.txt");   //the right way to link ifstream obj. to file
63     TextQuery tq;
64     tq.read_file(in);
65     cout << "Enter word to look for: ";
66     string s;
67     cin >>s;
68     set<vector<string>::size_type> loc=tq.run_query(s);
69     cout << loc.size() <<endl;
70     for (set<vector<string>::size_type>::iterator l_itr=loc.begin(); l_itr!=loc.end(); l_itr++)
71     {
72         cout << "Line " << *l_itr << ":" << (tq.lines_of_text)[*l_itr] << endl;
73     }
74     return 1;
75 }
76 
77 //Input "it", "she", "her", are OK
78 //but "Daddy" 因为后面接了一个",",所以不能成功执行
79 //若单词后面接标点符号,则标点符号会与单词一起组成string
80 //加入    for (string::size_type s=0;word[s]!='\0';s++)
81 //            {
82 //                while (ispunct(word[s]))
83 //                {
84 //                    word.erase(s);
85 //                }
86 //            }
87 //解决单词后面有标点的问题

 

posted on 2013-09-24 21:00  Rainbow0905  阅读(114)  评论(0)    收藏  举报