在C++中使用 seekg 时出现问题
Problems using seekg in C++
我正在通过这样的函数读取文件:
#include <iostream>
#include <fstream>
#include <string>
...
void readfile(string name){
string line;
int p = 0;
ifstream f(name.c_str());
while(getline(f,line)){
p++;
}
f.seekg(0);
cout << p << endl;
getline(f,line);
cout << line << endl;
}
小米文件有3行:
first
second
third
我期望输出:
3
first
相反,我得到:
3
(nothing)
为什么我的搜索不起作用?
因为如果流已到达文件末尾(eofbit
已设置),则seekg()
失败,这是由于您的getline
循环而发生的。正如 sftrabbit 所暗示的那样,调用clear()
将重置该位,并且应该允许您正确搜索。(或者你可以只使用 C++11,其中seekg
将清除eofbit
本身。
使用迭代器从文件中读取
std::fstream file( "myfile.txt", std::ios::out );
std::string data = std::string(
std::istreambuf_iterator<char>( file ),
std::istreambuf_iterator<char>() );
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- 使用 seekg() 读取C++中的文件时出现问题
- 在C++中使用 seekg 时出现问题
- ifstream seekg 有什么问题
- 同一文件上的 seekp()、seekg()、read() 和 write() 有问题
- 关于 ifstream 在 C++ 中的 seekg() 函数的问题