Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //http://www.youtube.com/user/thecplusplusguy
- #include <iostream> //for write out (cout)
- #include <fstream> //for file handling (ifstream)
- #include <vector> //for store the lines (vector)
- #include <string> //for store the strings
- #include <ctime> //for seed the random number generator (time(0))
- #include <cstdlib> //for random number generator (rand)
- using namespace std;
- int main()
- {
- char buf[500]; //max 500 character/line
- ifstream in("example.txt"); //read the example.txt file
- vector<string> lines; //create a vector, which contain strings
- srand(time(NULL)); //seed the random number generator
- //read all lines to the vector
- while(!in.eof()) //while we are not the end of the file
- {
- in.getline(buf,500); //read a line to the buf (max 500 character, from in, to buf)
- lines.push_back(buf); //push to the end of the lines vector
- }
- in.close(); //close the file, we don't need it anymore
- for(int i=0;i<10;i++) //get 10 random number
- {
- int randline=rand()%(lines.size()-1); //generate a random number, I use the -1 for the size, because it starts from 1 (if the vector 20 long, the max
- //number you get randomly is 20, but the biggest index is 19)
- cout << lines[randline] << endl; //write out the line
- }
- return 0;
- }
- /*
- solution 2, without read it to the memory
- #include <iostream> //for write out (cout)
- #include <fstream> //for file handling (ifstream)
- #include <ctime> //for seed the random number generator (time(0))
- #include <cstdlib> //for random number generator (rand)
- using namespace std;
- int main()
- {
- char buf[500]; //max 500 character/line
- ifstream in("example.txt"); //read the example.txt file
- int lines=0;
- srand(time(NULL)); //seed the random number generator
- //read all lines to the vector
- while(!in.eof()) //while we are not the end of the file
- {
- in.getline(buf,500); //read a line to the buf (max 500 character, from in, to buf)
- lines++;
- }
- for(int i=0;i<10;i++) //get 10 random number
- {
- in.clear();
- in.seekg(0,ios::beg);
- int randline=rand()%(lines-1)+1; //generate a random number, I use the -1 for the size, because it starts from 1 (if the vector 20 long, the max
- //number you get randomly is 20, but the biggest index is 19)
- for(int i=0;i<randline;i++)
- {
- in.getline(buf,500);
- }
- cout << buf << endl;
- }
- in.close(); //close the file, we don't need it anymore
- return 0;
- } */
Advertisement
Add Comment
Please, Sign In to add comment