【发布时间】:2011-10-09 22:48:57
【问题描述】:
例如,我有这个 test.txt 包含:
apple
computer
glass
mouse
blue
ground
然后,我想从文本文件中检索一个随机行。 这是我的代码:
ifstream file;
file.open("test.txt", ios::in);
char word[21];
int line = rand()%6 + 1;
for (int x = 0 ; x < line ; x++)
test.getline (word, 21);
cout << word;
问题是变量 'word' 总是包含第一行,无论给出什么随机数...
【问题讨论】:
-
您是否在此代码之前的某处播种生成器(通过调用
srand)? -
顺便说一句,我们知道您需要帮助,您不必明确说明,在有任何感谢之前请不要说“THX”;)
-
哦,我忘了打电话给 srand... 我现在就更新,谢谢