| | |
Reading in a random line from a file
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Apr 2007
Posts: 110
Reputation:
Solved Threads: 2
Hi. I am new to the forum and I had a question. I have looked around and haven't really been able to find exactly what I am looking for.
I am looking for the code in C++ to read in a random single line with spaces from a file.
This is the file I have...(example.txt)
the big green
forrest gump
blades of glory
glory road
animal house
pirates of the carribean
the seven little foys
the lord of the rings
the green mile
cast away
star wars
it
now and then
the princess bride
This is the code for a function I have so far, but it just prints out the entire file.
how do i change this so that it reads in just a random single line?
I am looking for the code in C++ to read in a random single line with spaces from a file.
This is the file I have...(example.txt)
the big green
forrest gump
blades of glory
glory road
animal house
pirates of the carribean
the seven little foys
the lord of the rings
the green mile
cast away
star wars
it
now and then
the princess bride
This is the code for a function I have so far, but it just prints out the entire file.
c++ Syntax (Toggle Plain Text)
void file(){ string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while (! myfile.eof()) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; }
how do i change this so that it reads in just a random single line?
Last edited by kylcrow; Apr 6th, 2007 at 2:22 pm.
1. Read in each line into a string array or std::vector.
2. Whilst at the same time incrementing a counter, which counts each line.
3. Using srand pick a number which is less than the max line count.
4. Use that number as the index to the array of strings/ vector and output to the screen.
Alternatively you can do something similar without the need for a temporary storage device (vector etc).
2. Whilst at the same time incrementing a counter, which counts each line.
3. Using srand pick a number which is less than the max line count.
4. Use that number as the index to the array of strings/ vector and output to the screen.
Alternatively you can do something similar without the need for a temporary storage device (vector etc).
Last edited by iamthwee; Apr 6th, 2007 at 2:25 pm.
*Voted best profile in the world*
I don't have my compiler so this is not tested.
I think it might always miss the first line. Meh?
C++ Syntax (Toggle Plain Text)
#include <cstdlib> #include <iostream> #include <fstream> #include <vector> #include <string> #include <ctime> class RandomCrap { public: int show(int p) { srand( ( unsigned )time( 0 ) ); int random_integer; random_integer = ( rand ( ) % p ) + 1; return random_integer; } }; int main() { std::ifstream read ("example.txt"); std::string line; std::vector < std::string > stuff; int counter = 0; while (getline(read, line, '\n')) { stuff.push_back( line ); counter++; } read.close(); RandomCrap a; std::cout << stuff[a.show( counter - 1 )]; std::cin.get(); return 0; }
I think it might always miss the first line. Meh?
Last edited by iamthwee; Apr 6th, 2007 at 3:30 pm.
*Voted best profile in the world*
•
•
Join Date: Dec 2006
Posts: 1,089
Reputation:
Solved Threads: 164
the basic problem here is that we need to select one item at random
when we do not know beforehand how many items there are. the most
common example of this in real code is when a random element has to
be picked from a list (size unknown). there is a well known algorithm to
do this without having to pass through the entire sequence:
the variable nlines counts the number of lines as they are read.
for any line, rand() % ++nlines == 0 is true with probability
1 / nlines. the first line is initially selected (with probability 1),
the second line replaces it with probability 1/2, the third line will
replace the survivor (either line one or line 2, each of which are
equally likely) with probability 1/3, and so on.therefore, for each
of the nlines lines seen so far is selected with probability
1/nlines.
if i remember right, this was first seen widely in some code
written by brian kernighan.
when we do not know beforehand how many items there are. the most
common example of this in real code is when a random element has to
be picked from a list (size unknown). there is a well known algorithm to
do this without having to pass through the entire sequence:
C++ Syntax (Toggle Plain Text)
string random_line( ifstream file ) { string line ; int nlines = 0 ; while( getline( file, line ) ) if( ( rand() % ++nlines ) == 0 ) break ; return line ; }
for any line, rand() % ++nlines == 0 is true with probability
1 / nlines. the first line is initially selected (with probability 1),
the second line replaces it with probability 1/2, the third line will
replace the survivor (either line one or line 2, each of which are
equally likely) with probability 1/3, and so on.therefore, for each
of the nlines lines seen so far is selected with probability
1/nlines.
if i remember right, this was first seen widely in some code
written by brian kernighan.
Last edited by vijayan121; Apr 6th, 2007 at 8:55 pm. Reason: add the last 2 lines
•
•
Join Date: Dec 2006
Posts: 1,089
Reputation:
Solved Threads: 164
THERE IS A SERIOUS ERROR IN THE PREVIOUS POST.
IT SHOULD BE
there is a well known algorithm to
do this without having to copy the entire sequence
into a buffer having random access :
•
•
•
•
there is a well known algorithm to
do this without having to pass through the entire sequence:
C++ Syntax (Toggle Plain Text)
string random_l[ine( ifstream file ) { string line ; int nlines = 0 ; while( getline( file, line ) ) if( ( rand() % ++nlines ) == 0 ) break ; return line ; }
there is a well known algorithm to
do this without having to copy the entire sequence
into a buffer having random access :
C++ Syntax (Toggle Plain Text)
string random_line( ifstream file ) { string line ; string selected_line ; // added int nlines = 0 ; while( getline( file, line ) ) if( ( rand() % ++nlines ) == 0 ) // break ; selected_line = line ; return selected_line ; }
Last edited by vijayan121; Apr 7th, 2007 at 2:11 am. Reason: add code tag
![]() |
Similar Threads
- C++ Reading from a text file (C++)
- choose a random element from a sequence (C++)
- how to move to the second line in C++ .txt file reading? (C++)
Other Threads in the C++ Forum
- Previous Thread: An OpenSource Database
- Next Thread: Merge Sort Code Not Working Properly In Vc++.code Is Given
| Thread Tools | Search this Thread |
api array based beginner binary bitmap c++ c/c++ calculator char char* class code coding compile compiler console conversion count data database delete deploy developer dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game getline givemetehcodez graph gui homeworkhelp homeworkhelper iamthwee ifstream input int integer java lib linker list loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference rpg sorting string strings struct temperature template text text-file tree url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






