C++ file IO seeking to a specific line -


for instance, have test.txt containing :

apple computer glass mouse blue ground 

then, want retrieve 1 random line text file. here's code :

ifstream file; file.open("test.txt", ios::in); char word[21];  int line = rand()%6 + 1; (int x = 0 ; x < line ; x++)    test.getline (word, 21);  cout << word; 

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

seed random number suggested comments above

#include <cstdlib> #include <ctime> #include <fstream> //...other includes , code  ifstream file; file.open("abc.txt", ios::in); char word[21]; srand( time(null) ); int line = rand()%6 + 1;  (int x = 0 ; x < line ; x++)    file.getline (word, 21);  cout << word; 

Comments

Popular posts from this blog

javascript - Iterate over array and calculate average values of array-parts -

iphone - Using nested NSDictionary with Picker -

objective c - Newbie question -multiple parameters -