How to get data from a txt file in C ++

The problem that I am facing is that I can create a text file, write the text once. I want to be able to add additional lines to it, if necessary, without creating a new file. my next problem is that I cannot get the output they need. eg. text file contains

start1
file_name | LNAME | PLA
end1

My goal is to get data only in start1 and end1 and return fname lname and ssn without a separator. here is my code

int main()
{
    fstream filestr;
    string line;

    filestr.open ("file.txt", fstream::in | fstream::out | fstream::app);
    if(!filestr.is_open())
    {
        cout << "Input file connection failed.\n";
        exit(1); 
    }
    else{
        filestr<<"Start2\n";
        filestr<< "middle|middle"<<endl;
        filestr<<"end2"<<endl;
        if(filestr.good()){
            while(getline(filestr, line) && line !="end1"){
                if(line !="Start1"){
                    //below this point the output goes screwy
                    while(getline(filestr, line,'|')){
                        cout<<"\n"<<line;
                    }
                }
            }
        }
        filestr.close();
    }
+3
source share
2 answers

Nearly:

, . , , ( ).

        filestr.seekg(0);

- , while :

                while(getline(filestr, line,'|')){
                    cout<<"\n"<<line;

. . , .

, :

            if(line !="Start1")
            {   
                std::stringstream   linestream(line);
              // ^^^^^^^^^^^^^^^^^^  Add this line

                while(getline(linestream, line,'|'))
                {         //  ^^^^^^^^^^ use it as the stream
                    cout<<"\n"<<line;
                }   
            }

PS: file.txt

start1
^^^^^ Note not Start1
+2
while(getline(filestr, line))
{
      if(line !="Start1" && line != "end1")
      {
          // Get the tokens from the string.           
      }
}
+1

All Articles