ifstream seekg 有什么问题
What's wrong with the ifstream seekg
我正在尝试查找并重新读取数据。但是代码失败了。
代码
std::ifstream ifs (filename.c_str(), std::ifstream::in | std::ifstream::binary);
std::streampos pos = ifs.tellg();
std::cout <<" Current pos: " << pos << std::endl;
// read the string
std::string str;
ifs >> str;
std::cout << "str: " << str << std::endl;
std::cout <<" Current pos: " <<ifs.tellg() << std::endl;
// seek to the old position
ifs.seekg(pos);
std::cout <<" Current pos: " <<ifs.tellg() << std::endl;
// re-read the string
std::string str2;
ifs >> str2;
std::cout << "str2: (" << str2.size() << ") " << str2 << std::endl;
std::cout <<" Current pos: " <<ifs.tellg() << std::endl;
我的输入测试文件是
qwe
输出为
Current pos: 0
str: qwe
Current pos: 3
Current pos: 0
str2: (0)
Current pos: -1
谁能告诉我怎么了? 当ifs >> str;
因为到达文件结束而结束时,它设置eofbit。
直到c++ 11, seekg()
不能从流的末尾寻找(注意:你的实际上可以,因为输出是Current pos: 0
,但这不是完全一致的:它应该失败查找或者它应该清除eofbit并查找)。
无论如何,要解决这个问题,您可以在ifs.seekg(pos);
ifs.clear();
。看起来在读取字符时,它击中了EOF并将其标记为流状态。当执行seekg()调用时,流状态不会改变,因此下一次读取检测到EOF位已设置并返回而不读取。
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- c++无值sort()的问题是什么?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 什么是钻石问题?是一系列问题还是特定问题?
- 格式说明符C++有什么问题
- 我应该在 main 函数中写什么来测试我的问题?
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 方法问题 - 什么会改变值,什么不会改变?什么是无效的?