【问题标题】:How to detect empty lines while reading from ifstream in C++如何在 C++ 中从 ifstream 读取时检测空行
【发布时间】:2016-04-08 12:02:44
【问题描述】:

当我从文件中读取时,我想检测空行。我试过line.empty()line.size()==0line=="",但是这些都不适合我。

有什么建议吗?

void readFile(const string & fn){
    ifstream fichier;
    string line;
    try{
        fichier.open(fn.c_str(),ifstream::in);
        while(getline(fichier,line))
        {
            if(line.empty())// i tried also line=="" and line.size()==0
            {
                cout<<"empty line!!"<<endl;
            }
            else{
                cout<<"Line:"<<line<<endl;
            }
        }
        fichier.close();

    }catch(const string & msg){
        if(fichier.is_open()) fichier.close();
        cout<<"Error !!";
    }
}

【问题讨论】:

  • 您确定这些行实际上是 为空的吗?里面没有空格?而您确实在输入文件中有“空”行吗?
  • 如果像line.clear()这样在每次迭代结束时清除该行会怎样?
  • 您能否添加一些文本行的示例,其中可能包含一些应该为空的文本行?
  • @Joachim Pileborg:是的,你是对的,我的文件中有一些空间,我没有检测到它们,因为我有一个大文件,现在当我删除行中的空格时,它的工作,谢谢!!
  • @NathanOliver 是的,我做到了,它有效,谢谢!!

标签: c++ file ifstream


【解决方案1】:

你可以这样做:

string buffer;
getline(fichier, buffer, '\n);
if(isEmpty(buffer)){
  //do whatever
}

如果您确定您的行完全为空(即没有空格、制表符或非文本字符,您的 isEmpty 函数可以类似于 return buffer=="";

如果它更复杂,并且你的换行符可以包含像 \t 这样的字符,你可以这样做:

bool isEmpty(string buffer){
  for (int i = 0; i<buffer.length(); i++{
    if (buffer[i] != '\t') //add chars you want to exempt here
      return false;
  }
return true;
}

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多