SaifAli JT
SaifAli JT

Reputation: 1

How do I make the code print the first line from the text file?

This is a simple code that searches a txt file for the string "G for Grapes" and prints each line as it goes. The file has the following text in it

  1. A for Apple
  2. B for Ball
  3. C for Cat
  4. D for Duck
  5. E for Elephant
  6. F for Football
  7. G for Grapes

But when the loop for reading it runs, It starts from B instead of A.

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

int main(){
    ifstream fin;
    string line;
    string finD = "G for Grapes";

    fin.open("sample.txt");

    getline(fin, line);

    for (unsigned int i = 1; getline(fin, line); i++)
    {
        cout << line << endl;

        if (line.find(finD, 0) != string::npos)
        {
            cout << "\n Fount it!\n In line no# " << i << endl;
        }
    }
    
    fin.close();

    cout << endl;
    
    return 0;
}

Upvotes: 0

Views: 375

Answers (1)

cigien
cigien

Reputation: 60308

In this code:

getline(fin, line);  // reads first line
    
for (unsigned int i = 1; getline(fin, line); i++)  // reads second line
{
   cout << line << endl;  // prints second line

You need to simply remove the call to getline that is outside the for loop, otherwise you are ignoring the first line, and not printing it out.

Upvotes: 3

Related Questions