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?
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 ();
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.