Read and Display any line from a text file using function printFile

So I know how to open and display lines from a text file but how do you display one line at a time based on a user-input number?
Any suggestions?

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

void printLine(fstream&);

int main()
{

string filename = "D:/EGR 125/HW 6/06HW Problem 8.4 Number 3";
string line;
ifstream inFile;

inFile.open(filename.c_str());
}

void printLine(fstream&)
{
ifstream inFile;
string line;

while (getline(inFile,line))
{
cout << line << endl;
}

return (line);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <string>

// first line is line number 1
std::string get_line( std::istream& input_stream, int line_number )
{
    std::string line ;
    
    // read and discard lines till we reach the required line
    for( int i = 0 ; i < line_number ; ++i ) std::getline( input_stream, line ) ;
    
    // if the stram is in a good state, we have read the line successfully, return it
    // otherwise, there is an error (eg. the file does not contain that many lines)
    return input_stream ? line : "" ; 
}

int main()
{
    const std::string file_name = __FILE__ ; // "D:/EGR 125/HW 6/06HW Problem 8.4 Number 3"
    std::ifstream file(file_name) ;

    int line_number = 6 ;
    std::cout << "line " << line_number << ": " << get_line( file, line_number ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/9456f44da36bd95c
Topic archived. No new replies allowed.