2011-07-21 21 views
0

例如,我有一个包含这个的test.txtC++文件IO寻求到一个特定的行

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; 

问题是变量“字”总是包含第一线,无论什么随机给定数......

+3

您是否在此代码之前的某个位置为生成器(通过调用'srand')播种? – littleadv

+0

如何定义'test'? –

+0

顺便说一句,我们知道你需要帮助,你不必明确说明,请不要在没有任何要谢谢之前说“THX”;) –

回答

4

种子随机数通过上述

的意见的建议
#include <cstdlib> 
#include <ctime> 
#include <fstream> 
//...other includes and code 

ifstream file; 
file.open("abc.txt", ios::in); 
char word[21]; 
srand(time(NULL)); 
int line = rand()%6 + 1; 

for (int x = 0 ; x < line ; x++) 
    file.getline (word, 21); 

cout << word; 
+0

将只会得到第一行中的多少字节,而每一行的字节数都不同。所以,它不是专门得到1行....我已经尝试过的代码,它只返回一行中的字符串的一部分... – Jason

+0

我知道我没有注意到,这就是为什么我张贴第二个片段。应该按预期工作。 – xeon111

+0

是getline(char *,int)将指针移动到下一行? THX的解决方案无论如何呵呵 – Jason

0

如果您想为大量的线路做这个过程中,这里是更有效的方式:

  • 创建一个可以保存字符串的数组。
  • 将每个单词放在数组中,使得数组索引=行号。
  • 现在生成随机数并用数组索引访问它。
相关问题