Thread: Read from file, output random line

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    59

    Read from file, output random line

    I have some of the code written down already, but I just don't know how I am going to display one line. I know how to use rand srand, and open a file, but I don't know how to cout just one line.

    I am really confused as to what to do. I've tried Google, but I don't know what I'm searching for so I'm getting horrible results.

    The code I have is:
    Code:
    #include <iostream>
    #include <fstream>
    #include <cstblib>
    #include <conio.h>
    #include <ctime>
    
    using namespace std;
    
    int var();
    int defu();
    
    int main()
    {
    	int choice;
    
    	cout << "1.  Open a variable file"	<< endl
    	     << "2.  Open the default file"	<< endl
    	     << "Enter your choice: ";
    		cin >> choice;
    
    		switch ( choice )
    		{
    			case 1:
    			{
    				var();
    				break;
    			}
    
    			case 2:
    			{
    				defu();
    				break;
    			}
    
    			default:
    			{
    				cout << "Invalid choice!" << endl
    				     << "Program closing...";
    				break;
    			}
    		}
    
    	getch();
    	return 0;
    }
    
    var()
    {
    	// initialize variables
    	srand ( ( unsigned ) time ( 0 ) );
    	string filename;
    	int line-n, yn, d;
    	int x = 0;
    
    	// prompt user for file
    	cout << "Enter the name of the file you wish to open:" << endl;
    		getline ( cin, filename );
    
    	// check to see if string is empty
    	if ( filename.empty() )
    	{
    		cout << "ERROR: No file name entered!" << endl;
    		return 0;
    	}
    
    	// if string isn't empty
    	else
    	{
    		// open file
    		inp.open ( filename.c_str() );
    
    		if ( !infile )
    		{
    			cout << "ERROR: Unable to open file" << endl;
    			return 0;
    		}
    		else
    		{
    			// perform the line counting
    			while ( !infile.eof() )
    			{
    				x++;
    				line-n = x;
    			}
    
    			// finaly, pick out a line and display it
    			while ( yn != 1 )
    			{
    				d = ( rand() %line-n ) +1;
    
    				// this is where I don't know what to do
    				if ( d ==
    This is my first program in awhile, so don't hate me for the syntax and, probably, numerous errors. Also, sorry for the indenting; it looks good in vi.

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    getline() can be used to read in one line of a file--just like reading in one line from cin:

    getline(infile, str);


    It doesn't matter what ifstream you read from: cin or infile. So, I think the first thing you need to do is get a count of how many lines are in the file:

    Code:
    int count = 0;
    while( getline(infile, str) ) 
    { 
         ++count;
    }
    Note: whenever you read from a file, you want to make your read statement the while loop conditional. That ensures that if there is an error while reading from the file, then reading from the file will cease without messing up your program. Most of the functions you use to read from a file return the ifstream object, e.g. infile, which will evaluate to false if there is an error--that includes eof which is considered a stream error.

    Once you have a count of the number of lines, then you can choose your random number. Once you have your random number, you can read one line at a time again until you get to that line number. However, that means you end up reading from the file twice, and reading from files is pretty slow, so you want to avoid doing it whenever possible.

    A better solution would be: while you are counting the lines, put each line in a string array(or even better a vector), and then after you are done counting, you will have all the input in the array. That will allow you to access a specific array element using your random number as the index value, which also means you won't have to trudge through every line to get to the line you want.
    Last edited by 7stud; 10-29-2005 at 01:51 PM.

  3. #3
    Registered User Bajanine's Avatar
    Join Date
    Dec 2001
    Location
    The most peaks over 10,000 feet!
    Posts
    396
    Is this a typo?
    Code:
    #include <cstblib>
    Favorite Quote:

    >For that reason someone invented C++.
    BLASPHEMY! Begone from my C board, you foul lover of objects, before the gods of C cast you into the void as punishment for your weakness! There is no penance for saying such things in my presence. You are henceforth excommunicated. Never return to this house, filthy heretic!



  4. #4
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    I hate to badger, but how would I go about entering each string into an array?

    Bajanine: Probably... I put a lot of headers, I must have had a plan for it. Too bad I can't think of what it is now.
    Last edited by Asbestos; 10-29-2005 at 02:24 PM.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    No, what Bajanine means is that
    Code:
    #include <cstblib>
    should probably be
    Code:
    #include <cstdlib>
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    how would I go about entering each string into an array?
    You would use a loop. And an array of strings. Something like this:
    Code:
    string s[10];
    
    for(int x = 0; x < 10; x ++) cin >> s[x];
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    Ah hah, thanks guys.

    I'll start working on it now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is there any way to read a line from a text file?
    By megareix in forum C Programming
    Replies: 13
    Last Post: 01-09-2009, 01:13 PM
  2. Searching Binary Files for a Pattern
    By CaptainMorgan in forum C Programming
    Replies: 16
    Last Post: 06-17-2007, 06:04 PM
  3. getline function to read 1 line from a text file
    By kes103 in forum C++ Programming
    Replies: 3
    Last Post: 10-21-2004, 06:21 PM
  4. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM