Ejercicio de biblioteca estándar de C ++: programa de consulta de texto

1. Introducción

El capítulo 12.3 del primer 5e de C ++ ilustra un ejemplo del uso de la biblioteca estándar: un programa de consulta de texto, donde la cadena de consulta se busca como una palabra (palabra), y la biblioteca estándar isringstream en la biblioteca sstream se usa para realizar una línea de contenido. Juicio de segmentación de palabras.

Aquí hay una modificación. Use la biblioteca estándar para ejercicios de ejemplo en los siguientes escenarios.
Método de coincidencia : la línea de texto solo debe contener una cadena y el método de palabra no está separado por caracteres en blanco;
método de búsqueda : cuando se busca una cadena especificada, la primera búsqueda es solo Realice la búsqueda y el juicio reales, y guarde el conjunto de resultados; si busca más tarde, el resultado se obtendrá directamente del último conjunto de resultados guardado;

2. Archivo de prueba

El contenido del archivo test.txt:

today is a good day
the girl is so beautiful
It was a beautiful morning. 
aloha
hehe
how beautiful
beautiful view

3. Ejecutar resultados

fs.good():  1
fs.rdstate():  0
 getline parse start
 read line 1:today is a good day
 read line 2:the girl is so beautiful
 read line 3:It was a beautiful morning.
 read line 4:aloha
 read line 5:hehe
 read line 6:how beautiful
 read line 7:beautiful view
 getline parse end
enter word to look for,or q to quit :beautiful
 [search] begin a new find action->
 [search] end
beautiful occurs 4 times
        (line 2 )the girl is so beautiful
        (line 3 )It was a beautiful morning.
        (line 6 )how beautiful
        (line 7 )beautiful view

enter word to look for,or q to quit :beautiful
 [find] you have do find action before,last find result:
beautiful occurs 4 times
        (line 2 )the girl is so beautiful
        (line 3 )It was a beautiful morning.
        (line 6 )how beautiful
        (line 7 )beautiful view

enter word to look for,or q to quit :hehe
 [search] begin a new find action->
 [search] end
hehe occurs 1 times
        (line 5 )hehe

enter word to look for,or q to quit :he
 [search] begin a new find action->
 [search] end
he occurs 2 times
        (line 2 )the girl is so beautiful
        (line 5 )hehe

4. Código de muestra

#include <fstream>   
#include <sstream>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
using namespace std;
using line_no = vector<string>::size_type;
class QueryResult;
class TextQuery {
    
    
public:
	TextQuery(ifstream&  ifs);
	QueryResult  find(const string&)  ;
private:
	ifstream& fs;
	shared_ptr<vector<string>> file; 
	map<string, shared_ptr<set<line_no>>>wm;
};

TextQuery::TextQuery(ifstream& ifs) :fs(ifs), file(new vector<string>)
{
    
    
	
	string text;
	//getline 需 #include <fstream> 
	int count = 0;
	cout << " getline parse start"  << endl;
	while (getline (fs, text)) {
    
    
		cout << " read line " << (++count) <<":"<< text<< endl;
		file->push_back(text); 
	}
	cout << " getline parse end"  << endl;
 
}
class QueryResult {
    
    
	friend ostream& print(ostream&, const QueryResult&);
public:
	QueryResult(string s, shared_ptr<set<line_no>>p, shared_ptr<vector<string>>f) 
		:sought(s), lines(p), file(f){
    
    }
private:
	string sought;
	shared_ptr<set<line_no>>lines;
	shared_ptr<vector<string>>file;
};
 

QueryResult TextQuery::find(const string & sought)  
{
    
    	 

	auto loc = wm.find(sought);
	if (loc != wm.end())
	{
    
    
		cout << " [find] you have do find action before,last find result:" << endl;
		return  QueryResult(sought, loc->second, file);
	}
	string text;
	//getline 需 #include <fstream>
	cout << " [search] begin a new find action->" << endl;
	shared_ptr<set<line_no>> lines;
	lines.reset(new set<line_no>); 
	
	int linenum = 0;
	for (string& text : *file)
	{
    
    
		if (text.find(sought) != string::npos)
		{
    
    
			//cout << "[find]find "<<sought<<" in line:"<<text << endl;
			lines->insert(linenum);
		}
		linenum++;
	} 
		/*
	for (line_no num = 0 ;num <(*file).size();num++)
	{
		if ((*file)[num].find(sought) != string::npos)
		{
			//cout << "[find]find "<<sought<<" in line:"<<text << endl;
			lines->insert(num);
		} 
	}*/
	cout << " [search] end" << endl;  
	wm.insert({
    
     sought,lines });
	return QueryResult(sought, lines, file); 
}
ostream&  print(ostream& os, const QueryResult &qr)
{
    
    
	os << qr.sought << " occurs " << qr.lines->size() <<  " times" << endl;
	for (auto num : *qr.lines)
		os << "\t(line " << num + 1 << " )" << *(qr.file->begin() + num) << endl;
	return os;
}
void runQueryies(ifstream & fs)
{
    
    
	TextQuery tq(fs);
	while (true) {
    
    
		cout << "enter word to look for,or q to quit :";
		string s;
		if (!(cin >> s) || s == "q") break;
		print(cout, tq.find(s)) << endl;
	}
}
int main(int argc,char** argv)
{
    
     
	string  filename("K:\\temp\\test.txt");  
	//string  filename(argv[0]);
	ifstream fs(filename);
	cout << "fs.good():  " << fs.good() << endl;
	cout << "fs.rdstate():  " << fs.rdstate() << endl;
	//cout << "fs.eof(): " << fs.eof() << endl;
	//cout << "fs.fail():  " << fs.fail() << endl;
	//cout << "fs.bad():  " << fs.bad() << endl;
	/*enum _Iostate
		{	// constants for stream states
		_Statmask = 0x17};

	static constexpr _Iostate goodbit = (_Iostate)0x0;
	static constexpr _Iostate eofbit = (_Iostate)0x1;
	static constexpr _Iostate failbit = (_Iostate)0x2;
	static constexpr _Iostate badbit = (_Iostate)0x4;
	*/
	if (!fs.good())
	{
    
    
		cout << "open file fail,please check whether the file is exist:" << filename << endl;
		return 0;
	}
	runQueryies(fs);
}
 

5. Materiales de referencia

"C ++ primer" versión china 5ª edición, [América] Stanley B. Lippman et al. Traducción de Wang Gang et al., Electronic Industry Press

Supongo que te gusta

Origin blog.csdn.net/skytering/article/details/106034307
Recomendado
Clasificación