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.

10-29-2005

7stud

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.

10-29-2005

Bajanine

Is this a typo?

Code:

#include <cstblib>

:p

10-29-2005

Asbestos

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.