开发者

C++ file IO seeking to a specific line

开发者 https://www.devze.com 2023-03-22 08:05 出处:网络
for instance, I have this test.txt containing : apple computer glass mouse blue ground then, I want to retrieve one random line from the text file.

for instance, I have this test.txt containing :

apple
computer
glass
mouse
blue
ground

then, I want to retrieve one random line from the text file. here's my code :

ifstream file;
file.open("t开发者_JAVA技巧est.txt", ios::in);
char word[21];

int line = rand()%6 + 1;
for (int x = 0 ; x < line ; x++)
   test.getline (word, 21);

cout << word;

the problem is the variable 'word' always contains the first line, no matter what random number given...


Seed the random number as suggested by the comments above

#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;


If you want to do this process for large number of lines, here is more efficient way:

  • Create an array which can hold strings.
  • Put each word in array such that array index=line no.
  • Now generate random number and access it with array index.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号