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

Par*_*mbo 1 c++

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

1) Hello
2) HELLO
3) hEllO
Run Code Online (Sandbox Code Playgroud)

我将如何阅读,比如说第 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;
}
Run Code Online (Sandbox Code Playgroud)

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

cdh*_*wie 5

首先,你的循环条件是错误的。 不要使用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.
}
Run Code Online (Sandbox Code Playgroud)