Reputation: 1
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
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
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