在C++中,跳过读取文件中的行可以通过以下几种方法实现:
std::istream::ignore()
函数:#include<iostream>
#include <fstream>
#include<limits>
int main() {
std::ifstream inputFile("input.txt");
if (!inputFile) {
std::cerr << "Failed to open file"<< std::endl;
return 1;
}
// 跳过第一行
inputFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::string line;
std::getline(inputFile, line);
std::cout << "Second line: "<< line<< std::endl;
return 0;
}
std::istream::seekg()
函数:#include<iostream>
#include <fstream>
int main() {
std::ifstream inputFile("input.txt");
if (!inputFile) {
std::cerr << "Failed to open file"<< std::endl;
return 1;
}
// 获取文件中第一行的长度
std::streampos pos = inputFile.tellg();
inputFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::streampos length = inputFile.tellg() - pos;
// 将文件指针移回第一行的开头
inputFile.seekg(pos);
// 跳过第一行
inputFile.ignore(length);
std::string line;
std::getline(inputFile, line);
std::cout << "Second line: "<< line<< std::endl;
return 0;
}
这两种方法都可以实现跳过读取文件中的行。具体使用哪种方法,取决于具体的需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云