How to do a search in txt file?

1

How do I search a .txt file that contains, for example, a list of numbered names, type:

1 - João
2 - Maria
...

I would enter the desired number and the return would be the name, or say nothing was found. It can be in C, or C ++.

    
asked by anonymous 05.05.2015 / 16:02

2 answers

1

In C ++ you can do the following:

string getNome(string numero) {

    ifstream ifs( "ficheiro.txt" );
    string linha;
    string resultado = "Nada foi encontrado";

    while( getline( ifs, linha) ) {
        if (linha.find(numero, 0) != string::npos) {
           //cout << "encontrou: " << numero << " linha: " << linha << endl;
           resultado = linha.substr(linha.find('-', 0) + 2, linha.length() );
        }
    }

    return resultado;
}

Following the comment from @pmg, and if you intend to do multiple searches you can try something like this:

#include<iostream>
#include<string>
#include<fstream>
#include<map>

class MapaNomes{
public:
    MapaNomes(string nomeFicheiro) {
       ifstream ifs(nomeFicheiro);
       string linha;
       string numero;

       while(getline(ifs, linha)) {
          numero = linha.substr(0, linha.find('-', 0), -1);
          nome = linha.substr(linha.find('-', 0) + 2, linha.length());

          nomes.insert(pair<int, string>(stoi(numero), name));
      }
    }

    string getNome(int numero) {
        map<int, string>::iterator it = nomes.find(numero);
        return (it != nomes.end()) ? it->second : "Nada foi encontrado";
    }
private:
    map<int, string> nomes;
}

int main(int argc, char* argv[]) {
    MapaNomes mNomes("lista_nomes.txt");

    cout << "Procurar 1, Resultado: " << mNomes.getNome(1) << endl;
    cout << "Procurar 2, Resultado: " << mNomes.getNome(2) << endl;
    cout << "Procurar 3, Resultado: " << mNomes.getNome(3) << endl;
    cout << "Procurar 4, Resultado: " << mNomes.getNome(4) << endl;

    return 0;
}

Your file is assumed to be formatted consistently. If this is not the case, you have to adjust and improve how the number and corresponding name are being captured.

But can I ask why I do this in C or C ++? Is it an exercise only?

    
05.05.2015 / 16:38
1

To search for element number 11 you use awk!:

awk '$1==11{print $3}' ficheiro.txt

If you really have to use C

#include <stdio.h>

int main(){
  char s[100]; int n;
  scanf("%d",&n);
  sprintf(s,"awk '$1==%d {print $3}' ficheiro.txt", n);
  system(s);
}
    
19.05.2015 / 16:56