gpt4 book ai didi

c++ - 如何使用 fstream (C++) 从文件中读取特定行

转载 作者:行者123 更新时间:2023-11-27 23:02:33 37 4
gpt4 key购买 nike

我是一名 n00b C++ 程序员,我想知道如何从文本文件中读取特定行。例如,如果我有一个包含以下行的文本文件:

1) Hello
2) HELLO
3) hEllO

我将如何阅读,比如第 2 行并将其打印在屏幕上?这是我目前所拥有的..

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

int main(int argc, char *argv[])
{
string sLine = "";
ifstream read;

read.open("input.txt");

// Stuck here
while(!read.eof()) {
getline(read,1);
cout << sLine;
}
// End stuck

read.close();

return 0;
}

评论部分中的代码是我卡住的地方。谢谢!!

最佳答案

首先,你的循环条件是错误的。 Don't use while (!something.eof()).它并不像您想象的那样。

您所要做的就是跟踪您在哪一行,并在阅读第二行后停止阅读。然后您可以比较行计数器,看看您是否到达了第二行。 (如果没有,则文件包含的行少于两行。)

int line_no = 0;
while (line_no != 2 && getline(read, sLine)) {
++line_no;
}

if (line_no == 2) {
// sLine contains the second line in the file.
} else {
// The file contains fewer than two lines.
}

关于c++ - 如何使用 fstream (C++) 从文件中读取特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26288145/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com