C++でファイルの特定の行にジャンプする方法は何ですか?
C ++では、ファイルの特定の行に直接ジャンプすることはできません。ファイルの内容を一行ずつ読み取り、判断して特定の行に到達する必要があります。以下は、この機能を実現する方法を示すサンプルコードです:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string line;
int target_line = 5; // 指定跳转到第5行
if (file.is_open()) {
int current_line = 1;
while (getline(file, line)) {
if (current_line == target_line) {
std::cout << "第" << target_line << "行的内容为: " << line << std::endl;
break;
}
current_line++;
}
file.close();
} else {
std::cout << "无法打开文件" << std::endl;
}
return 0;
}
上記の例では、ファイルexample.txtを開き、第5行に移動することを指定しました。ファイルの内容を行ごとに読み込み、現在の行数を数えながら、カウントが目標行番号と一致すると、その行の内容を出力してループから抜けます。
実際の応用では、ファイルの存在や読み取りエラーなどに対して、より多くのエラー処理と容認処理が必要になるかもしれません。