这是一个简单的代码,它在txt文件中搜索字符串“g for grapes”
,并打印每一行。 该文件中包含以下文本
但是当读取它的循环运行时,它从B开始,而不是从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;
}
在此代码中:
getline(fin, line); // reads first line
for (unsigned int i = 1; getline(fin, line); i++) // reads second line
{
cout << line << endl; // prints second line
您只需删除对for
循环之外的getLine
的调用,否则您将忽略第一行,并且不会将其打印出来。