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 getlin开发者_如何学JAVAe works:
while(1)
{
if(!file.good())
break;
getline(file,line);
student.name=line;
getline(file,line);
student.phone=line;
current->insert(student);
}
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!
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.
精彩评论