我有两个问题:
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;
}
编辑:好的,你们中的一些人的建议很有意义。该字符串可能被读取为“\nmystring”。所以我想我现在的问题是,我将如何从字符串中删除第一个 \n ?