How do you get the whole line where a given word is stored and store it in a variable?

advertisements

i am a beginner in the C++ world, i need to get the whole line where a given word is and store it into a variable.

my TXt file has this structure :
clients.txt
085958485 Roland Spellman [email protected]
090545874 KATHLEEN spellman [email protected]
056688741 Gabrielle Solis [email protected]

so the program requests to the user to enter the id of the person, the id is always the first number or word in the line. the user enters then 090545874 the program has to be able to find the 090545874 in the text file and then get the whole line where it is stored into a variable.

i know how to find a word in a text file but i don't know how to get the whole line into a variable. so at the end my variable has to store

variable = 090545874 KATHLEEN spellman [email protected] 4878554

after that, i am able to delete the entire line or record. i use this code to enter the data into the txt file

      struct person{       

      char id[10];
      char name[20];
      char lastname[20];
      char email[10];
      } clientdata;

      ofstream clientsfile;
      clientsfile.open ("clientes.dat" , ios::out | ios::app);

      if (clientsfile.is_open())
      {
      cout<<"   ENTER THE ID"<<endl;
      cin>>clientdata.id;
      clientsfile<<clientdata.id<<" ";                              

      cout<<"   ENTER THE NAME"<<endl;
      cin>>datoscliente.name;
      clientsfile<<clientdata.name<<" ";

      cout<<"   ENTER THE LAST NAME"<<endl;
      cin>>clientdata.lastname;
      clientsfile<<clientdata.lastname<<" ";

      cout<<"   ENTER THE LAST EMAIL"<<endl;
      cin>>clientdata.email;
      clientsfile<<clientdata.email<<" ";

then i request to the eu to enter the id and what i need to do is not to find the id only, it's to get the whole line where the id is so if the user enters 090545874 , i need to find it in the text file , but i need to get teh whole line in this case 090545874 KATHLEEN spellman [email protected] so i need to store that into a new variable string newvariable; newvariable = 090545874 KATHLEEN spellman [email protected]


To read files one line at a time, you can use the std::getline function defined in the <string> header (I'm assuming you're using the fstream library as well):

#include <fstream>
#include <string>

int main(int argc, char** argv) {
    std::ifstream input_file("file.txt");
    std::string line;

    while (true) {
        std::getline(input_file, line);
        if (input_file.fail())
            break;

        // process line now
    }

    return 0;
}

What's nice about the function std::getline, though, is that it allows for this much cleaner syntax:

#include <fstream>
#include <string>

int main(int argc, char** argv) {
    std::ifstream input_file("file.txt");
    std::string line;

    while (std::getline(input_file, line)) {
        // process line now
    }

    return 0;
}