Home > Net >  C getline function missing the first line of txt file
C getline function missing the first line of txt file

Time:03-09

I have written a function to read from .txt file and build a linked list, but the function missed the first line of the file. Anyone have any idea why that happens?

output:

//empty line  
gmail  
San Francisco  
123456

.txt file

person1
gmail
San Francisco
123456

readFile function

void list::readFile(std::string fileName){
    fstream fs;
    string dummy = "";
    string firstline;
    record * previous = new record;
    record * temp = new record;
    int recordCount = 0;
    fs.open(fileName, ios::in | ios::binary);
        do{
            std::getline(fs, temp->name);
            std::getline(fs, temp->email);
            std::getline(fs, temp->address);
            fs >> temp->phoneNo;
            std::getline(fs, dummy);
            recordCount  ;

            if(head == NULL){
                head = temp;
                previous = temp;
                tail = temp;
            } else {
                previous->next = temp;
                previous = temp;
                tail = temp;
            }

        } while(!fs.eof());
    // } else {
    //     cout << "there's no record in the file yet." << endl;
    // }

    cout << head->name << endl;
    cout << head->address <<endl;
    cout << head->email << endl;
    cout << head->phoneNo << endl;
}

CodePudding user response:

You create a single node so every iteration through the loop you overwrite the previously read values.

In the second iteration of the while loop your first call to getline presumably fails and sets the value of name to an empty string. As the stream is now in a failed state the rest of your reads are ignored and finally the loop breaks at the end of the loop.

This might be closer to what you wanted:

    int recordCount = 0;
    fs.open(fileName, ios::in | ios::binary);
        while(fs) {
            record * temp = new record;
            std::getline(fs, temp->name);
            std::getline(fs, temp->email);
            std::getline(fs, temp->address);
            fs >> temp->phoneNo;
            if (!fs) {
                // Reading failed, delete the temporary and exit the loop
                delete temp;
                break;
            }
            std::getline(fs, dummy);
            recordCount  ;

            if(head == NULL){
                head = temp;
                previous = temp;
                tail = temp;
            } else {
                previous->next = temp;
                previous = temp;
                tail = temp;
            }

        }

Your code could be made memory leak safer by using smart pointers to ensure temp is never leaked even if exceptions are thrown.

  • Related