ParadizeLimbo
ParadizeLimbo

Reputation: 33

How to read a specific line from file using fstream (C++)

I'm a n00b C++ programmer, and I would like to know how to read a specific line from a text file.. For example if I have a text file containing the following lines:

1) Hello
2) HELLO
3) hEllO

How would i go about reading, let's say line 2 and printing it on the screen? This is what i have so far..

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

int main(int argc, char *argv[])
{
    string sLine = "";
    ifstream read;

    read.open("input.txt");

    // Stuck here
    while(!read.eof()) {
         getline(read,1);
         cout << sLine;
    }
    // End stuck

    read.close();

    return 0;
}

The code in bewteen the comments section is where I'm stuck. Thanks!!

Upvotes: 2

Views: 18856

Answers (2)

Kostya
Kostya

Reputation: 1572

If you don't need conversion to strings, use istream::read, see here http://www.cplusplus.com/reference/istream/istream/read/

Upvotes: 0

cdhowie
cdhowie

Reputation: 168988

First, your loop condition is wrong. Don't use while (!something.eof()). It doesn't do what you think it does.

All you have to do is keep track of which line you are on, and stop reading once you have read the second line. You can then compare the line counter to see if you made it to the second line. (If you didn't then the file contains fewer than two lines.)

int line_no = 0;
while (line_no != 2 && getline(read, sLine)) {
    ++line_no;
}

if (line_no == 2) {
    // sLine contains the second line in the file.
} else {
    // The file contains fewer than two lines.
}

Upvotes: 7

Related Questions