gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:03:20 25 4
gpt4 key购买 nike

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

当前代码:

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

关于c++ - 使用getline从输入文件打印时如何忽略空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com