im writing a program to help me understand on rand fucntion i dont get how to use it with a file that has a bunch of characters i think i would have to do it in a loop so it could be random and set srand (time(NULL));
by all means do so but the most up-to-date way of generating random numbers in C++ is using the <random> library - search this forum for several examples last few weeks
grab a just one line
use std::getline() to read the file by line into std::string, save the lines in a std::vector<std::string>, std::random_shuffle the vector and pick-off any particular element like vec[0], etc
"use std::getline() to read the file by line into std::string, save the lines in a std::vector<std::string>, std::random_shuffle the vector and pick-off any particular element like vec[0], etc "
i want to use rand() not the library
the things is i have character not numbers
std::string random_line_from( std::string file_name )
{
std::string selected_line ; // the randomly chosen line
std::ifstream file(file_name) ; // open the file for reading
std::string current_line ; // the current line read from the file
std::size_t line_number = 1 ;
while( std::getline( file, current_line ) ) // for each line in the file
{
// the current line becomes the selected line with a probability of 1 / line_number
// the first line is selected with a probability of 1
// the second line replaces the selected line with a probability of 1/2
// so now, each line so far being the selected line has a probability of 1/2
// the third line replaces the selected line with a probability of 1/3
// so now, each of the three lines so far being the selected line has a probability of 1/3
// etc.
if( ( std::rand() % line_number ) == 0 ) selected_line = current_line ;
++line_number ;
}
return selected_line ;
}
// assumes that no line in the file is longer than 4095 characters
const std::size_t MAX_LINE_SZ = 4096 ; // +1 for the null-character at the end
char* random_line_from( constchar* file_name, char selected_line[MAX_LINE_SZ] )
{
selected_line[0] = 0 ; // initialise to a null string
std::ifstream file(file_name) ; // open the file for reading
char current_line[MAX_LINE_SZ] ; // the current line read from the file
std::size_t line_number = 1 ;
while( file.getline( current_line, MAX_LINE_SZ ) ) // for each line in the file
{
// the current line becomes the selected line with a probability of 1 / line_number
// the first line is selected with a probability of 1
// the second line replaces the selected line with a probability of 1/2
// so now, each line so far being the selected line has a probability of 1/2
// the third line replaces the selected line with a probability of 1/3
// so now, each of the three lines so far being the selected line has a probability of 1/3
// etc.
if( ( std::rand() % line_number ) == 0 ) std::strcpy( selected_line, current_line ) ;
++line_number ;
}
return selected_line ;
}