使用 getline 从输入文件打印时如何忽略空白行
How to ignore blank lines when printing from input file using getline
我正在尝试打印文件的内容,但我不确定如何忽略文件中的空白行。
当前代码:
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
}
相关文章:
- 无法通过空白将文本文件行分隔为矢量
- 在fstream期间忽略空行
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 概念TS检查忽略私有访问修饰符
- C++宏忽略之后的内容
- Python中的for循环与C++有何不同
- 不知道某个东西是否被忽略会引入未定义的行为吗
- clang整洁10忽略了我的NOLINT命令
- If语句在c++中被忽略
- 错误:在为指针赋值时,void值没有被忽略
- 为什么stream::忽略未按预期工作
- C++忽略使用字符串流进行读取的文本文件中的空白
- 将空白字符替换为 %20 的字符串,忽略所有尾随空格
- 如何使一个整数向量忽略空白,并在C++中的每个元素上加2
- 忽略空白字符
- 在文件中搜索字符串(逐行),忽略单词之间空白的大小
- 如何忽略c++ regex中记号之间的空白(自由空格模式)
- 使用getline()忽略空白/制表符/换行符
- 如何在c++中使用字符串getline从文本文件中读取时忽略/跳过空白
- 保存到文件时,会忽略空白后的单词