How can I read a random line from text file. After I get the word I need to count the letters.

bool word(char *Filename){

ifstream file;
file.open(Filename);

//add code.

return true;
}

Edited 5 Years Ago by alexchen: n/a

Well, you can try this:

1) Count the number of lines in the file

2) Do this:

rand_no = rand() % count; // where count is the no. of lines in the line.

3) Now, use a loop to iterate to that line.

PS:rand()

Thanks.Now I need to count the letters in the string.

bool word(char *Filename,int number){



ifstream file;
file.open(Filename);


int r=rand() % number + 1;


string output;


for(int i=0; i<r; i++) getline(file,output);


cout<<output<<endl;

return true;
}

Do you really need help counting the characters in the string? Look at the methods associated with a string object.

You probably need to just have a quick look at the methods in the std::string class, try this :o)

Comments
Isn't that exactly what I said 6 hours ago? Don't post for the sake of posting - give useful NEW information.

I found a warning.Can you solve this problem

bool word(char *Filename){


int r,number;

ifstream file;
file.open(Filename);

file>>number;

srand(time(NULL));
r=rand() % number+1;

string input,output;

for(int i=0; i<r; i++) getline(file,input);




return true;
}

Warning 1 warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data

Thanks.

bool word(char *Filename){


int r,number;

ifstream file;
file.open(Filename);

file>>number;

srand ( (unsigned)time ( NULL ) );
r=rand() % number+1;

string input;

for(int i=0; i<r; i++) getline(file,input);
cout<<input<<endl;



return true;
}

Edited 5 Years Ago by alexchen: n/a

This question has already been answered. Start a new discussion instead.