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

Recommended Answers

All 8 Replies

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 can use a char or string.

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

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

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

time() returns a type time_t srand() wants an unsigned int
Look up casting in your book.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.