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.