【问题标题】:How to ignore blank lines when printing from input file using getline使用getline从输入文件打印时如何忽略空白行
【发布时间】:2019-12-03 05:57:12
【问题描述】:

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

当前代码:

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 语句来解决这个问题,但它似乎不起作用。

感谢任何帮助。

【问题讨论】:

    标签: c++ ifstream getline


    【解决方案1】:

    逻辑

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

    【讨论】:

    • 非常全面的答案:)
    【解决方案2】:

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

        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
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2012-01-15
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多