次の数行のコードがあります。
QFile file("h:/test.txt");
file.open(QFile::ReadOnly | QFile::Text);
QTextStream in(&file);
bool found = false;
uint pos = 0;
do {
QString temp = in.readLine();
int p = temp.indexOf("something");
if (p < 0) {
pos += temp.length() + 1;
} else {
pos += p;
found = true;
}
} while (!found && !in.atEnd());
in.seek(0);
QString text = in.read(pos);
cout << text.toStdString() << endl;
アイデアは、特定の char シーケンスのテキスト ファイルを検索し、見つかった場合、ファイルを最初から検索されたテキストの出現までロードすることです。テストに使用した入力は次のとおりです。
this is line one, the first line
this is line two, it is second
this is the third line
and this is line 4
line 5 goes here
and finally, there is line number 6
そして、ここで奇妙な部分が来ます-検索された文字列が最後の行を除いていずれかの行にある場合、期待される動作が得られます。それは完全にうまく機能します。
しかし、最後の 6 行目にある文字列を検索すると、結果は常に 5 文字短くなります。7 行目であれば結果は 6 文字短くなります。検索文字列が最終行にある場合、結果は常にlineNumber - 1
文字分短くなります。
それで、これはバグですか、それとも明らかな何かが欠けていますか?
編集: 明確にするために、これを行うための代替方法を求めているのではなく、なぜこの動作が発生するのかを尋ねています。