【问题标题】:C++ Problem with using getline for strings in a text file在文本文件中使用 getline 处理字符串的 C++ 问题
【发布时间】: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++


    【解决方案1】:

    是的,因为 getline() 函数调用读取第一行。

    然后你进去做一个 infile >> 行,从第二行开始读取。

    如果您的文件中有更多行,您会看到它会跳过每隔一行。

    【讨论】:

    • 谢谢,这有助于澄清正在发生的事情。我使用 while(infile >> first >> last >> phone >> email) 作为字符串来设置类值,它工作得很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多