How to fetch a random line from a text file in C++
In this tutorial, we are going to learn how to fetch a random line from a text file in C++. This is very easy to do. We have to find a random number using rand() function and get a line from the text file.
Fetch a random line from a text file in C++
To fetch a random line from a text file in C++, we need to follow the given steps.
- Save the file in the same directory as the program.
- Use ifstream to operate on the file. Include fstream header to use this.
- Call the function srand() with argument ‘time(0)’ or ‘time(NULL)’ to make sure rand() function returns different random number for each call.
- Count the number of total lines in the file using getline() function of C++. If you don’t know how to do it. See here: Count the number of lines in a text file in C++
- Store the lines of the text file in a string vector using push_back() function. If you don’t know about push_back() function, See this: push_back() and pop_back() function in C++
- Generate a random number lying between 0 and count of total lines using rand() function and modulus operator.
- Fetch the line for which the line index is equal to the random number. Assuming the indexing starts from 0.
Here is the example program for fetching a random line from a text file. See the code.
#include<iostream> #include<stdlib.h> #include<fstream> #include<time.h> #include<vector> using namespace std; int main() { string line; vector<string> lines; srand(time(0)); //input file stream ifstream file("A_file.txt"); //count number of total lines in the file and store the lines in the string vector int total_lines=0; while(getline(file,line)) { total_lines++; lines.push_back(line); } //generate a random number between 0 and count of total lines int random_number=rand()%total_lines; //fetch the line where line index (starting from 0) matches with the random number cout<<lines[random_number]; return 0; }
The output is like this:
Second
The text file in the given program has ten lines and every line has a string specifying the line number. If I run the program again, I get a different random number, hence different outputs. For example,
Eighth
Thank you.
Why am I unable to use this more than once? If I use it a second time i get “conversion from ‘time_t’ to ‘unsigned int’, possible loss of data” from srand(time(0));
The function time() returns time_t and srand() takes unsigned int as input. The statement “srand(time(0))” involves an implicit cast from time_t to unsigned_int. For some reason, your system is facing a loss of data while this conversion takes place. Try the following statement that does explicit casting– “srand((unsigned int)time(0))”
How can I do the same but make the program read a line from 4 text files (randomly) instead of 1?