简体   繁体   English

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

[英]How to read a specific line from file using fstream (C++)

I'm a n00b C++ programmer, and I would like to know how to read a specific line from a text file.. For example if I have a text file containing the following lines: 我是n00b C ++程序员,我想知道如何从文本文件中读取特定行。例如,如果我有一个包含以下行的文本文件:

1) Hello
2) HELLO
3) hEllO

How would i go about reading, let's say line 2 and printing it on the screen? 我将如何阅读第2行,然后将其打印在屏幕上? This is what i have so far.. 这是我到目前为止所拥有的..

#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;
}

The code in bewteen the comments section is where I'm stuck. 在注释部分之间的代码是我遇到的问题。 Thanks!! 谢谢!!

First, your loop condition is wrong. 首先,您的循环条件是错误的。 Don't use while (!something.eof()) . 不要使用while (!something.eof()) It doesn't do what you think it does. 它没有按照您的想法做。

All you have to do is keep track of which line you are on, and stop reading once you have read the second line. 您要做的就是跟踪您所在的行,并在阅读完第二行后停止阅读。 You can then compare the line counter to see if you made it to the second line. 然后,您可以比较行计数器以查看是否到达第二行。 (If you didn't then the file contains fewer than two lines.) (如果没有,则文件包含少于两行。)

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.
}

如果您不需要转换为字符串,请使用istream :: read,请参阅此处http://www.cplusplus.com/reference/istream/istream/read/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM