【发布时间】:2020-02-07 22:06:43
【问题描述】:
我正在编写一个程序,它接受一个文本文件并将文本文件中的值输入到类函数和一个向量中。我正在使用一个使用 getline 从文本文件中收集值的 while 循环。我遇到的问题是 getline 功能正常,但仅在文本文件的第二行。它似乎要么跳过文件的第一行,要么第一行被第二行覆盖。
代码如下
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);
}
}
文本文件包含
Kortni Neal 555-555-5555 kdd195@google.com
Aubrey Knight 444-444-4444 akk5@google.com
控制台输出
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?
感谢您的帮助。
【问题讨论】:
标签: c++