#include <iostream>
#include <fstream>
#include <string>
#include <vector>
std::ifstream iFile;
std::string string;
std::vector<std::streampos> titlePos;
int main()
{
iFile.open("presets.txt", std::ios_base::app);
if (!iFile.is_open())
{
std::cout << "iFile presets isnt open" << std::endl;
}
while (!iFile.eof())
{
iFile >> string;
if (string == "%title")
{
iFile >> string;
titlePos.emplace_back(iFile.tellg());
}
}
for (int x = titlePos.size() - 1; x != -1; --x)
{
iFile.seekg(titlePos[x]);
std::cout << titlePos[x] << std::endl;
std::cout << iFile.tellg() << std::endl;
}
return 0;
}
出于某种原因,listPos[x]
的cout
都是常见的(我认为(,但一旦我将streampos
值转移到ifstream iFile
,它们都会导致输出-1(我认为这是一个错误(。
我不明白为什么传递值会导致错误,也不明白我该如何找到错误的原因。
IN";"presets.txt";
%title loc1
%title loc2
%title loc3
输出
-1
-1
26
-1
11
-1
从流读取数据失败后(不包括eof
(,tellg
和seekg
也将失败并返回-1
。
while (!iFile.eof())
还意味着您在读取值之前而不是在读取值之后检查流状态。在使用该值之前,您应该检查每个操作是否成功,这是titlePos
中最后一个条目为-1
的原因。
要将流重置为good
,您需要调用clear()
。
这应该会起作用:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
std::ifstream iFile;
std::string string;
std::vector<std::streampos> titlePos;
int main()
{
iFile.open("presets.txt", std::ios_base::app);
if (!iFile.is_open())
{
std::cout << "iFile presets isnt open" << std::endl;
}
while (iFile)
{
if (!(iFile >> string))
{
break;
}
if (string == "%title")
{
if (!(iFile >> string))
{
std::cout << "error reading stringn";
break;
}
titlePos.emplace_back(iFile.tellg());
}
}
iFile.clear();
for (int x = titlePos.size() - 1; x != -1; --x)
{
iFile.seekg(titlePos[x]);
std::cout << titlePos[x] << std::endl;
std::cout << iFile.tellg() << std::endl;
}
return 0;
}