Random access text file

I have a txt file with n lines. I want to access a random line and print it on the screen. The fuction fstream.seekg(a, ios::beg) is useful, but it only makes the cursor go to the character number a, not line number a. How can I make the cursor go to the beginning of a random line?
Last edited on
closed account (SECMoG1T)
Why not use a simple loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 int num;//hold the line ti read
 int count=1;
 string temp;
 ifstream in ("lines.txt");
 if (!in){cout <<"file not found\n"; return-1;}
 
  cout <<"what line do you want to display? ";
  cin>> num;

   while (in)
      {
         getline (cin, temp,'\n');
           
          if (count==num){ cout <<" line "<<num <<" is: "<<temp<<endl; break; }
          
           ++count; 

        }
        
       in.close ();
    
Last edited on
Thanks for replying to my quesiton. Is this the only way? I think what we need to use random access method since there are a big number of lines. If we use a simple loop like this, it will take more time to find the line.
Topic archived. No new replies allowed.