Xeo*_*Xeo 36
循环你的方式.
#include <fstream>
#include <limits>
std::fstream& GotoLine(std::fstream& file, unsigned int num){
file.seekg(std::ios::beg);
for(int i=0; i < num - 1; ++i){
file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
return file;
}
Run Code Online (Sandbox Code Playgroud)
将搜索指针设置file为行的开头num.
使用以下内容测试文件:
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)
Testprogram:
int main(){
using namespace std;
fstream file("bla.txt");
GotoLine(file, 8);
string line8;
file >> line8;
cout << line8;
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出: 8
这是一个有效且简洁的示例,std::getline()其中线条是否具有相同的长度:
#include <iostream>
#include <fstream>
#include <string>
const int LINE = 4;
int main() {
std::ifstream f("FILE.txt");
std::string s;
for (int i = 1; i <= LINE; i++)
std::getline(f, s);
std::cout << s;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81078 次 |
| 最近记录: |