使用 getline 从输入文件打印时如何忽略空白行

How to ignore blank lines when printing from input file using getline

本文关键字:何忽略 空白 打印 getline 输入 文件 使用      更新时间:2023-10-16

我正在尝试打印文件的内容,但我不确定如何忽略文件中的空白行。

当前代码:

if(option == "-ps"){
while(getline(instream, str)){
if(str.length() == 0){
continue;
}
cout << str << endl;   
}
}

文件内容

Department meeting | 2019 |10 |29 |9:30 aM  |15 
Meeting with Bob | 2019 |10 |29 |8:30 aM  |15 
Meeting with Jim | 2019 |10 |29 |9:00 aM  |15 
Doctor's appointment | 2019 |10 |29 |10:30 aM  |15 
Meeting with Bob | 2019 |10 |29 |11:30 aM  |15 
Lunch meeting with dean | 2019 |10 |29 |11:45 aM  |15 
Lunch with the guys | 2019 |10 |29 |12:30 pM  |60 
Lunch with the guys | 2019 |10 |29 |12:30 pM  |60 
Lunch with the guys | 2019 |10 |29 |12:30 pM  |60 
Meeting With BOB | 2019 |10 |29 |1:30 pM  |15 
Chair meeting | 2019 |10 |29 |2:30 PM  |15 
Meeting WITH Bob | 2019 |10 |29 |3:30 pm  |20 
Fishing with Donald and Donald|2019|11|30|8:14AM| 115
Fishing with Donald and Billy|  2019|12|11  | 2:45 PM|15
Appointment with Donald|2019  |12|5|8:56PM |115
Appointment with Fred|2019|12|1|8:30PM|50

Lunch|2019|12  | 1|10:58PM |115
Fishing with Bob and Fred|2019 |12| 3| 2:45PM|10
Skiing with Juedes|  2019|12  | 8|9:15 am|60 

我当前的代码将打印出文件内容,但空白行也打印出来。我试图用第二个 if 语句解决这个问题,但它似乎不起作用。

任何帮助,不胜感激。

逻辑

if(str.length() == 0){
continue;
}

如果存在包含一个或多个空格字符的行,则不起作用。也许你遇到了他们。您可以将其更改为使用:

if ( is_empty_line(line) )
{
continue;
}

哪里

bool is_empty_line(const& line)
{
for (char c : line )
{
if ( !std::isspace(c) )
{
return false;
}
}
return true;
}

您可以使用std::all_of来简化该功能。

bool is_empty_line(const& line)
{
return std::all_of(line.begin(), line.end(), [](char c) { return std::isspace(c); });
}

你的代码几乎是正确的,试试这个:

getline(instream, str); 
// Keep reading a new line while there is 
// a blank line 
while (str.length()==0 ) 
getline(instream, str); 
cout << str << << endl; 

另一种方式:

while (getline(instream, str))
{
if (str== "") continue; // Skip blank line
... // Do stuff with non-blank line
}