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

Two functions working with getline on same fstream object c++

本文关键字:函数 两个 getline fstream 同一个 对象      更新时间:2023-10-16

我有以下问题。我有这两个函数。第一个是从文本文件中读取联系人信息,联系人用符号"#"分隔,就像这样-

//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++;
    }
}

所有的文件都有一个"当前的读取位置",当你从文件中读取时,这个位置是先进的。除非您改变位置,否则您将始终读取文件中的下一个内容,此时"#2"是下一个记录。

我建议你解决它,是简单地有一个函数读取数据,当它涉及到一个新的记录标记,然后它初始化字符串的空向量,并将记录的行读到这个向量,然后将这个向量传递给解析内容的函数。

类似下面的伪代码:

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);
    }
}