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

时间:2013-12-04 21:18:04

标签: c++ string for-loop file-io getline

我差不多用我的程序来读取联系人数据,除非我读取它,某些行重复并跳过其他行。例如,这就是目前发生的事情:

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

1 个答案:

答案 0 :(得分:0)

此代码:

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);
//      ^^^^^^^^^^^^^^^^^
相关问题