从一个txt文本文档中查找某个单词出现的次数和相应的行数。
方法:
1将文本文档内容按每行读入到vector<string>容器中。
2.将vector<string>中每个string拆分成相应单词。
3.将单词和出现的行数作为一组,放入map<string,set<string::size_type>容器中。
4.将用户输入的单词从map中进行匹配,并且输出相应数量和行号。
我们可以将其封装成一个类 textquery类。
构造函数接受一个ifstream类型的文件流。
另外一个成员函数query接受一个用户的输入并且查找和输出信息。
代码如下:
#include "pch.h"
#include <iostream>
#include<fstream>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
void runquery(ifstream&); //获取用户要查询的单词,和相应文章的流
int main()
{
ifstream a("xiaoming.txt");
if (a) {
runquery(a);
}
else
cout << "打开失败" << endl;
}
void runquery(ifstream& b) {
textquery tq(b);
while (true) {
cout << "enter word to look for, or q to quit:";
string s;
if (s == "q" || !(cin >> s)) break;
tq.query(s);
}
}
//类头文件
#ifndef PCH_H
#define PCH_H
#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<memory>
using namespace std;
class textquery {
private:
vector<string> a;
map<string, set<string::size_type>> b;
public:
textquery(ifstream&); //将文本内容以单词和出现的行号的方式放入成员变量map中
void query(string); //返回查询结果
};
#endif
//类函数实现
#include "pch.h"
#include<string>
#include<sstream> //isstringstream
#include<fstream>
using namespace std;
textquery::textquery(ifstream& a) {
string b;
while (getline(a, b)) {
this->a.push_back(b);
auto n = this->a.size();
istringstream line(b);
string word;
while (line >> word) {
this->b[word].insert(n);
}
}
}
void textquery::query(string word) {
auto hello = b.find(word);
if (hello== b.end()) {
cout << "文本里没有这个单词" << endl;
}
else {
cout << hello->first << "出现了" << hello->second.size() << "次" << endl;
for (auto a = hello->second.begin(); a != hello->second.end(); ++a) {
cout << "第" << *a << "行:" << endl;
cout << " " << this->a[*a-1] << endl;
}
}
}
没有使用c++ primer中的方式,将查询和输出存入一个类中,并且也没有使用shared_ptr智能指针。
本题在c++ primer的第P430