Ahmed
Ahmed

Reputation: 3458

How does getline() work?

I have this piece of code that I use to load a linked list from a binary or a text file .. It works fine for text files but it always loads an extra line in the binary case , So I need to know how getline works:

while(1)
{
     if(!file.good())
          break;

     getline(file,line);
     student.name=line;

     getline(file,line);
     student.phone=line;

     current->insert(student);
}

Upvotes: 1

Views: 6446

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

it always loads an extra line

Of course: you are inserting what you have read without verifying that it was read successfully.

You need to move your file.good() test after the reading attempt.

Furthermore, there’s no need to test for good explicitly, the result of getline already gives you the status. The canonical way of loading simple data from a file inside a loop is something as follows:

student_type student;
while (getline(file, student.name) and getline(file, student.phone))
    current->insert(student_type(student)); // Makes explicit copy!

Upvotes: 3

Yochai Timmer
Yochai Timmer

Reputation: 49251

getline() reads a \n or EOF terminated line.

So in binary files it doesn't mean much.

Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delim if this parameter is specified, or '\n' otherwise). The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation.

Upvotes: 2

Related Questions