如何使代码打印文本文件中的第一行?

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

本文关键字:一行 代码 何使 打印 文本 文件      更新时间:2023-10-16

这是一个简单的代码,用于在txt文件中搜索字符串"G for Grapes"并打印每一行。该文件包含以下文本

  1. A 代表苹果
  2. B 代表球
  3. C 代表猫
  4. D 代表鸭子
  5. E 代表大象
  6. F 代表足球
  7. G 代表葡萄

但是当读取它的循环运行时,它从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的调用,否则您将忽略第一行,并且不会将其打印出来。