user836910
user836910

Reputation: 484

how to retrieve data from a txt file in c++

the problem that im having is this that i am able to create a text file, write to a text once. i want to be able to add more lines to it when necessary without creating a new file. my next problem is that i cant seem to get the output that im looking for. eg. text file contain

start1
fname|lname|ssn
end1

my aim is to only get data within start1 and end1 and return fname lname and ssn without the delimiter |. 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();
    }

Upvotes: 3

Views: 4719

Answers (2)

Loki Astari
Loki Astari

Reputation: 264401

Nearly:

When you open a file for appending the read position is at the end. So before you start reading you need to seek back to the beginning (or close and re-open).

        filestr.seekg(0);

The second probelem is that you nested while loop does not check for end:

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

This breaks up the line. But it does not stop at the end of the line. it keeps going until it reaches the end of the file.

What you should do is take the current line and treat it as its own stream:

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

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

PS: In the file.txt

start1
^^^^^ Note not Start1

Upvotes: 2

Jagannath
Jagannath

Reputation: 4025

while(getline(filestr, line))
{
      if(line !="Start1" && line != "end1")
      {
          // Get the tokens from the string.           
      }
}

Upvotes: 1

Related Questions