2 つの質問があります。
1) コードが selected_line 文字列の先頭に改行を追加するのはなぜですか?
2) ファイルからランダムな行を返すために使用しているアルゴリズムは十分であり、問題は発生しないと思いますか?
サンプル ファイルは次のとおりです。
line
number one
#
line number two
私のコード:
int main()
{
srand(time(0));
ifstream read("myfile.dat");
string line;
string selected_line;
int nlines = 0;
while(getline(read, line, '#')) {
if((rand() % ++nlines) == 0)
selected_line = line;
}
// this is adding a \n at the beginning of the string
cout << selected_line << endl;
}
編集: OK、あなたの何人かが提案したことは非常に理にかなっています。文字列はおそらく "\nmystring" として読み取られています。だから私は今私の質問だと思います、文字列から最初の \n をどのように削除しますか?