如何在c ++中识别空行?

时间:2014-03-13 18:34:19

标签: c++ file input

我正在从文件中读取信息。我需要一个计数器来计算有多少文本填充行。如果有任何空白行,我需要该计数器停止(即使该空行后面有文字填充行)。

我如何做到这一点,因为我不确定如何识别一个空白行来停止那里的计数器。

谢谢!

6 个答案:

答案 0 :(得分:1)

如果您使用std::getline,则可以通过检查刚刚读取的std::string是否为空来检测空行。

std::ifstream stream;
stream.open("file.txt");
std::string text;
while(std::getline(stream,text))
    if(!text.size())
        std::cout << "empty" << std::endl;

答案 1 :(得分:1)

我建议使用std::getline

#include <string>
#include <iostream>

int main()
{
    unsigned counter = 0;
    std::string line;

    while ( std::getline(std::cin, line) && line != "" ) ++counter;

    std::cout << counter << std::endl;
    return 0;
}

由于@Edward发表了关于处理空白的评论,这可能很重要 当只有空格的行被认为是“空行”时,我建议将其改为:

#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>

int main()
{
    unsigned counter = 0;
    std::string line;

    while ( std::getline(std::cin, line) && 
            std::find_if_not( line.begin(), line.end(), std::isspace != line.end() ) {
        ++counter;
    }

    std::cout << counter << std::endl;
    return 0;
}

它非常冗长,但优点是它使用std::isspace来处理所有不同类型的空格(例如' ''\t''\v'等等......如果你正确处理它们,你不必担心。

答案 2 :(得分:0)

在C ++ 11中,您可以使用

std::isblank

答案 3 :(得分:0)

在循环中,将所有行逐个读取到单个string变量中。您可以使用std::getline函数。

每次读取该变量后的行,请检查其length。如果它为零,则该行为空,在这种情况下break为循环。

但是,检查空行并不总是正确的事情。如果你确定这些线是空的,那就没关系。但是如果你的“空”行可以包含空格:

123 2 312 3213 
12 3123 123
              // <---  here are SPACEs, is it "empty" ?
123 123 213
123 21312 3

那么你可能不需要检查“零长度”,而是“所有字符是否为空格”。

答案 4 :(得分:0)

没有错误检查,没有保护,只是简单的例子......没有经过测试,但你得到了要点。

#incldue <iostream>
#include <string>

using namespace std;

int main()
{
  string str = "";
  int blank = 0, text = 0;
  ifstream myfile;
  myfile.open("pathToFile");
  while(getline(myfile,str))
  {
    if(str == "")
    {
      ++blank;
    }
    else
    {
      ++text;
    }
  }
  cout << "Blank: " << blank << "\t" << "With text: " << text;
  return 0;
}

答案 5 :(得分:0)

只需检查字符串长度并使用行计数器。当字符串长度为零(即字符串为空)时,打印行计数器。示例代码供您参考

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
int i=0;
if (myfile.is_open())
    {
     while ( getline (myfile,line) )
     {
      i++;
      // cout << line << '\n';
      if(line.length()==0) break;
      }
      cout << "blank line found at line no. " <<i<<"\n";;
      myfile.close();
   }

 else cout << "Unable to open file";

 return 0;
 }