一次从.txt文件中读取两行 - C++ getline/流
Read two lines at a time from a .txt file - C++ getline/ streams?
我正在使用下面的代码来读取文件,搜索给定的字符串并显示该行。但是我想阅读我在文件的字符串搜索中找到的内容的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
标志变量,该变量是在找到匹配项时设置的,然后在找到匹配项后再次循环,以便您可以获得下一行。测试标志以确定是否在上一个循环中找到匹配项。
相关文章:
- C++ 从文本文件中读取每两行,并且在矢量中是安全的
- 这两行代码有什么区别
- 矩阵中的内积两行C++与特征
- 使用 c++ 中的 getline 函数连续读取两行
- 一条线和两行声明之间的差异
- 为什么c中的一些函数名称用两行写
- 代码行在两行后不起作用
- 使用 Qt 获取 csv 文件中两行之间所有行
- OpenCV中图像的以下两行有什么区别
- 在C 中使用两个GetLine(CIN,S)
- Fstream 在两行后不会从文本文件中读取
- C++:如何在两行中为一个字符串和一个整数分配相同的输入
- SDL:程序运行正常;仅绘制两行像素
- c++如何将文本文件中的一行拆分为两行,然后将每行存储到两个不同的数组中
- 以下两行代码的另一个等效C++
- 在两行上打印类似"FirstnSecond"的字符串
- 这两行有什么区别?在不同位置使用整数
- C++更有效的方法将这两行代码写成一行短行
- 一次从.txt文件中读取两行 - C++ getline/流
- 运行程序时,它让我在名称后输入两行?请帮忙