問題の説明
一連の行を含むファイルがあります。あ
ファイル 1:
"Hello How are you"
"The cat ate the mouse"
ユーザーが入力として指定した行の開始と終了に基づきます。ファイルの各行に移動して抽出したいと思います。
たとえば、ユーザーが1、17と入力した場合、サイズが17文字の1行目に移動する必要があります。彼は、ファイル内の任意の行番号を指定できます。
ファイル C++ の特定の場所から次の Answer Read を読みました。でもよくわからなかった。なぜ行は同じサイズでなければならないのですか? ファイル内のすべての行の開始と終了に関する情報がある場合。直接アクセスできないのはなぜですか?
ソースコード
Read Data From Specified Position in File Using Seekgに触発された次のコードを使用しようとしましたが、なぜ行を抽出できませんでしたか?
#include <fstream>
#include <iostream>
using namespace std::
void getline(int, int, const ifstream & );
int main()
{
//open file1 containing the sentences
ifstream file1("file1.txt");
int beg = 1;
int end = 17;
getline(beg,end, file1);
beg = 2;
end = 20;
getline(beg,end, file1);
return 0;
}
void getline(int beg, int end, const ifstream & file)
{
file.seekg(beg, ios::beg);
int length = end;
char * buffer = new char [length];
file.read (buffer,length);
buffer [length - 1] = '\0';
cout.write (buffer,length);
delete[] buffer;
}