简体   繁体   中英

C++ Problem with using getline for strings in a text file

I am writing a program that takes a text file and inputs the values from the text file into class functions and a vector. I am using a while loop that uses getline to collect the values from the text file. The issue I am having is that getline functions properly, but only on the second line of the text file. It seems to be either skipping the first line of the file or the first line is somehow overwritten by the second line.

Code as follows

void readContacts(vector<Person>& contacts, ifstream& infile)
{
    Person temp;
    string line;

    cout << " " << endl;
    cout << "File opening ... " << endl;

    while(getline(infile, line))
    {
        cout << " " << endl;

        infile >> line;
        temp.setFirstName(line);
        cout << "First Name: " << line << endl;

        infile >> line;
        temp.setLastName(line);
        cout << "Last Name: " << line << endl;

        infile >> line;
        temp.setPhone(line);
        cout << "Phone Number: " << line << endl;

        infile >> line;
        temp.setEmail(line);
        cout << "Email: " << line << endl;

        contacts.push_back(temp);

    }
}

The text file contains

Kortni Neal 555-555-5555 kdd195@google.com
Aubrey Knight 444-444-4444 akk5@google.com

The console outputs

Welcome to your address book manager!
Please enter a file to read your contacts from (include extension): contacts.txt

File opening ...

First Name: Aubrey
Last Name: Knight
Phone Number: 444-444-4444
Email: akk5@google.com

First Name:
Last Name:
Phone Number:
Email:

File read. Closing the file from read mode.

Menu:
0. Exit
1. Display Address Book
2. Add Contact
What would you like to do?

Thanks for your help.

Yes it does, because the getline() function call reads the first line.

Then you go in and do a infile >> line, which reads starting from the second line.

If you had more lines in your file, you would have seen that it would have skipped every other line .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM