Reading multiple lines from a file using getline()

You are trying to read each line twice.

while (getline(inFile, firstName)) // reads the line
    {
        // reads the next line and overwrites firstName!
        inFile >> firstName >> lastName >> num1 >> num2;

Change it to:

while ( inFile >> firstName >> lastName >> num1 >> num2 )
{
    fullName = firstName + " " + lastName;
    cout << fullName << " " << num1 << " " << num2 << endl;
}

EDIT: To answer your questions:

How does getline() work?
Reads the entire line up to ‘\n’ character or the delimiting character specified. http://www.cplusplus.com/reference/string/string/getline/?kw=getline

After reading the line, the control goes to the next line in the file.
Also, it returns a boolean value of true if the read operation was successful, else false.

The extraction operator truncates on all whitespaces by default. It also returns a boolean value indicating whether the operation was successful.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)