在同一个fstream对象上使用getline的两个函数
Two functions working with getline on same fstream object c++
我有以下问题。我有这两个函数。第一个是从文本文件中读取联系人信息,联系人用符号"#"分隔,就像这样-
//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);
}
}
相关文章:
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 两个父类的构造函数的序列
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- 如何从两个不同的函数传递参数
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板
- 如何比较两个函数的速度和性能
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 有一个构造函数,但有两个析构函数
- 为什么系统日志有两个不同的函数声明?
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- C++ 关于两个类构造函数的问题
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 如何在构造器的成员初始值设定项列表中调用两个函数?
- 如何将这两个函数组合成一个实现?
- 将函数两个向量合并为第三个向量
- C++朋友函数两个数字的加法