Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

Getting specific lines in an input file.

Ok my question is how would I grab certain lines in a input file? lets say the input file has these sentences:

input.txt

Showing line 1
Showing line 2
showing line 3
etc...

now how would I get a specific line?

I know how to get first line by using

getline(file,str) //assuming string str; and ifstream file;
0
jschmuff
Asked:
jschmuff
  • 3
  • 2
  • 2
1 Solution
 
Infinity08Commented:
If the lines don't have a fixed length, then you'll have to read one line at a time until you reach the line you need (discarding all lines you read, except the last).

If the linesDO have a fixed length, you can set the file pointer to the correct location, and then read the line.
0
 
jkrCommented:
For a general approach, you can

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

ifstream is("input.txt");

vector<string> vLines;

while(!is.is_eof()){

  string sLine;

  getline(is,sLine);

  vLines.push_back(sLine);
}

// show 3rd line
cout << vLines[2] << eof; // 2 because indices are zero-based
0
 
jschmuffAuthor Commented:
so there is no way set a spot to start after?
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
jschmuffAuthor Commented:
jkr>> what is the bracket for after vLine.push_back(sline);
0
 
Infinity08Commented:
>> so there is no way set a spot to start after?

You can save a position in a file that you can go back to later by using tellg and seekg :

        http://www.cplusplus.com/reference/iostream/istream/tellg.html
        http://www.cplusplus.com/reference/iostream/istream/seekg.html

but of course you'd still have to get to the position you want first before you can use tellg.
0
 
jschmuffAuthor Commented:
Oh haha never mind I didnt see the beginning bracket for the while
0
 
jkrCommented:
>>what is the bracket for after vLine.push_back(sline);

Um, what bracket? The one that ends the 'while' loop?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now