一次从.txt文件中读取两行 - C++ getline/流

Read two lines at a time from a .txt file - C++ getline/ streams?

本文关键字:两行 getline C++ 一次 文件 txt 读取      更新时间:2023-10-16

我正在使用下面的代码来读取文件,搜索给定的字符串并显示该行。但是我想阅读我在文件的字符串搜索中找到的内容的immediate next line。我可以递增行号以获得下一行,但我需要在文件上再次使用 getline 吗?

这是我的代码:

#include <string>
#include <iostream>
#include <fstream>
    int main()
    {
        std::ifstream file( "data.txt" ) ;
        std::string search_str = "Man" ;
        std::string line ;
        int line_number = 0 ;
        while( std::getline( file, line ) )
        {
            ++line_number ;
            if( line.find(search_str) != std::string::npos )
            {
                std::cout << "line " << line_number << ": " << line << 'n' ;
                std::cout << ++line_number; // read the next line too
            }
        }
        return (0);
    }

这是我文件的内容:

Stu
Phil and Doug
Jason
Bourne or X
Stephen
Hawlkings or Jonathan
Major
League or Justice
Man
Super or Bat

您不需要另一个std::getline调用,但您需要一个标志来避免它:

#include <string>
#include <iostream>
#include <fstream>
int main()
{
    std::ifstream file( "data.txt" ) ;
    std::string search_str = "Man" ;
    std::string line ;
    int line_number = 0 ;
    bool test = false;
    while(std::getline(file, line))
    {
        ++line_number;
        if (test)
        {
            std::cout << "line " << line_number << ": " << line << 'n' ;
            break;
        }
        if( line.find(search_str) != std::string::npos )
        {
            std::cout << "line " << line_number << ": " << line << 'n' ;
            test = true;
        }
    }
    return (0);
}

是的,您将需要getline函数来读取下一行。

    while( file && std::getline( file, line ) )
    {
        ++line_number ;
        if( line.find(search_str) != std::string::npos )
        {
            std::cout << "line " << line_number << ": " << line << 'n' ;
            std::cout << ++line_number; // read the next line too
            std::getline(file, line);  // then do whatever you want.
        }
    }

请注意 while 子句中 file 的用法,这很重要。 iStream 对象可以计算为布尔值,相当于 File.good()。您要检查状态的原因是第二个getline()函数可能会到达文件的末尾并引发异常。您还可以在第二次getline调用后添加检查,如果!file.good(),则添加break

std::getline(file, line);  // then do whatever you want.
if(line.good()){
   // line is read stored correctly and you can use it
}
else{
  // you are at end of the file and line is not read
  break;
}

那么就不需要检查了。

您需要

创建一个新的 bool 标志变量,该变量是在找到匹配项时设置的,然后在找到匹配项后再次循环,以便您可以获得下一行。测试标志以确定是否在上一个循环中找到匹配项。