两个函数在同一个fstream对象c ++上使用getline

时间:2014-07-27 11:36:45

标签: c++ getline

我有以下问题。我有这两个功能。第一个是从txt文件中读取联系人信息,联系人用符号“#”分隔,如下所示 -

//sample txt file
#1
Name: AAA
Phone: 08782634
Phone: 0245637
Date: 23.34
Phone: 324324324
#2
Name: BBB
Phone: 99999

并找到每个联系人的长度(每个'#'之间的行数)。 第二个调用第一个,然后打印联系人,但它打印第二个联系人,而不是第一个联系人。

来自第一个函数的getline是否有可能以某种方式更改流,因为第二个函数在没有第一个函数的情况下使用它时非常有效(对于const int的硬编码容量)?

int Contact::FindNumberOfFields(std::ifstream& in)
{
    char* buffer = new char [1024];
    int cnt = 0;
    int i = 0;
    int pos = 0;
    while(in)
    {
        in.getline(buffer, 1024);
        if (strchr(buffer, '#'))
        {
            while (in.getline(buffer, 1024))
            {
                if (!strchr(buffer, '#') && strlen(buffer))
                {
                    cnt++;
                }
                else
                {
                    return cnt;
                }
            }


        }
    }
    in.clear();
    in.close();
    delete [] buffer;
}

void Contact::ReadContactFromStream(std::ifstream& in)
{
    SetCapacity(FindNumberOfFields(in));
    // cout << GetCapacity() << endl; // output is five, correct
    while(in)
    {
        if (addedFields >= GetCapacity()) // works correct when addedFields >= hardcored int (5) and removing SetCapacity(in) from code
        {
            break;
        }
        contactTypes[addedFields] = CreateObjectFromLine(in);
        addedFields++;
    }

}

1 个答案:

答案 0 :(得分:1)

所有文件都有“当前读取位置”,当您从文件中读取该位置是高级时。除非你change the position,否则你将始终阅读文件中的下一个内容,目前"#2"是下一个记录。

我建议你解决它,就是只需要一个读取数据的函数,当它涉及一个新的记录标记时,它会初始化一个空的vector字符串,并读取记录的行进入此向量,然后将此向量传递给一个解析内容的函数。

类似下面的伪代码:

std::getline(stream, line);
for (;;)
{
    if (line is start of record)
    {
        std::vector<std::string> current_record;
        while (std::getline(stream, line))
        {
            if (line is start of record)
                break;  // Break out of inner loop
            else
                current_record.push_back(line);
        }

        parse_record(current_record);
    }
}