如何使代码打印文本文件中的第一行?
How do I make the code print the first line from the text file?
这是一个简单的代码,用于在txt文件中搜索字符串"G for Grapes"
并打印每一行。该文件包含以下文本
- A 代表苹果
- B 代表球
- C 代表猫
- D 代表鸭子
- E 代表大象
- F 代表足球
- 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
的调用,否则您将忽略第一行,并且不会将其打印出来。
相关文章:
- 读取最后一行代码算法 - c++ 时出现问题
- 需要将一行代码从C++ Qt翻译成PyQt
- 在一行代码中理解 index++
- 我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?
- a = !5 < a;在这一行代码中究竟做了什么?
- std::vector 从一行代码清空到下一行代码
- 我如何使一行代码可以选择,但在已经选择过一次后不重新选择
- C++在 while 循环后添加一行代码会导致错误
- 一行代码的Arduino运行时间
- 如何在一行代码中使用花括号语法创建带有QJsonObjects的QJsonArray
- 是否可以使用一行代码从 std::cin 中提取格式化输入
- 有人可以解释一下工会在这一行代码中是如何工作的,以及数字是如何交换的
- 如何用一行代码连接两个矢量
- 为什么在这一行代码中同时使用 EOF 和 '