对于循环文件,数据正在重复并跳过其他行c++

for loop file data is repeating and skipping other lines c++

本文关键字:c++ 其他 于循环 循环 数据 文件      更新时间:2023-10-16

我几乎完成了读取联系人数据的程序,除了在读取时,某些行重复并跳过其他行。例如,这就是当前发生的情况:

Name: Herb  SysAdmin
Address: 27 Technology Drive
Age: 27 Technology Drive
Phone: 25
Type: WORK

它重复地址,但跳过电话。下面的代码。

int EnterContact(string contacts, ListofContacts list)
    // first number from the file depicting
{
    // constant
    ifstream inFile;            //input file stream object
    inFile.open("contacts.txt");
    // variables
    std:: string name,
        address,
        phone,
        contactType;
    string line;
    int age;
    int conNum = 0;
    inFile >> conNum;
    cout << endl;
    cout << "There are " << conNum << " contacts in this phone." << endl;
    for (int x = 0; x < conNum; x++)
    {
        getline(inFile, line);
        getline(inFile, name);
        getline(inFile, address);
        inFile >> age >> phone >> contactType;
        list[x] = Contact(name, address, age, phone, GetType(contactType));
    }
    //close the file
    inFile.close();
    return conNum;
}

如果有任何想法,或者我只是遗漏了一行代码,我们将不胜感激。

我的输入文件如下:

3
Herb SysAdmin
27 Technology Drive
25
850-555-1212
WORK
Sally Sallster
48 Friendly Street
22
850-555-8484
FRIEND
Brother Bob
191 Apple Mountain Road
30
850-555-2222
RELATIVE

此代码:

for (int x = 0; x < conNum; x++)
{
    getline(inFile, line);
    getline(inFile, name);
    getline(inFile, address);
    inFile >> age >> phone >> contactType;
    list[x] = Contact(name, address, age, phone, GetType(contactType));
}

是错误的,因为您将格式化的输入与未格式化的输入混合在一起,而没有清除提取到conNum和随后的contactType后留下的换行符。

要修复它,请使用std::ws:

getline(inFile >> std::ws, line);
//      ^^^^^^^^^^^^^^^^^
相关文章: