我正在做一个项目,我需要从一个文本文件中读取多个列表。除了读取它们,它还会根据读入的整数报告一些计算。文件读取在列表开头给出的标记处结束。
我用来测试的列表是:
9999 //sent value
636.9 // number to be ignored
First
4
8
15
16
23
42
Second
0.0
9999
我遇到的问题是,我的代码正确读取并存储了第一个列表的数据,但是当循环再次经过时它没有读取第二个列表。
我的主循环是:
infile >> sent;
infile >> inX;
while (!infile.fail())
{
inX = 0;
while (inX != sent)
{
int dSize = 0;
storeNames(listNames, infile);
ReadData(theData, infile);
cout << listNames[count] << endl;
cout << "Size is\t\t\t" << theData.size() << endl;
if (theData.size() >= 1)
{
ComputeStats(theData, meanValue, secondHigh);
DisplayStats(meanValue, secondHigh);
dSize = theData.size();
inX = theData[dSize - 1];
}
theData.clear();
count++;
}
}
读取数据函数为:
void ReadData(vector<int>& theData, ifstream& in)
{
if (in.is_open())
{
int number;
while (in >> number)
{
theData.push_back(number);
}
}
}
最后 storeNames 函数是:
void storeNames(vector<string>& listNames, ifstream& in)
{
string name;
in >> name;
listNames.push_back(name);
}
非常感谢您的帮助!
最佳答案
while (in >> number)
考虑到上面的代码,你是否在失败后恢复流状态? readData 将消耗所有内容,之后需要恢复流的状态,如果您想再次读取,请将 seekg 移回。
恢复istream状态可以查到here
是否需要移动 seekg 取决于您是否要再次使用相同的数据,否则您可能希望将流指针移动到下一个数据部分。
关于c++ - 读取多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32553045/