【问题标题】:for loop file data is repeating and skipping other lines c++for循环文件数据重复并跳过其他行c ++
【发布时间】:2013-12-21 13:51:45
【问题描述】:

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

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

【问题讨论】:

  • 你的输入文件是什么样的?
  • 等一下,我不知道如何在 cmets 上格式化
  • 我现在包含了我的输入文件
  • 我的猜测是您打印Contact 对象内容的代码有问题。当您的代码中显然是 int 时,我不确定如何解释年龄打印为字符串这一事实。
  • 你用什么来打印输出?还有Contact的构造函数代码是什么?

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


【解决方案1】:

这段代码:

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);
//      ^^^^^^^^^^^^^^^^^

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2014-07-30
    • 2015-05-17
    • 2023-03-08
    相关资源
    最近更新 更多