1

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!!

mkobit
  • 34,772
  • 9
  • 135
  • 134
ParadizeLimbo
  • 23
  • 1
  • 1
  • 3
  • Related to your use of eof http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Niall Oct 09 '14 at 21:29
  • Files are abstractions over named chunks of bytes; as such, there is no way to find where a specific line starts in the file without scanning through all the preceding bytes and counting the newlines. If you need to retrieve many specific lines, you can scan the file once looking for the offsets corresponding to each line start, then use this mapping for quick lookups. – Cameron Oct 09 '14 at 21:30
  • What do you expect this to do: `getline(read,1)`? – Galik Oct 09 '14 at 21:58
  • @Galik I thought it would read line 1 – ParadizeLimbo Oct 10 '14 at 00:43

2 Answers2

5

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.
}
Community
  • 1
  • 1
cdhowie
  • 133,716
  • 21
  • 261
  • 264
0

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

Kostya
  • 1,466
  • 1
  • 9
  • 15