如何在C++中从ifstream读取时检测空行

How to detect empty lines while reading from ifstream in C++

本文关键字:检测 读取 ifstream C++ 中从      更新时间:2023-10-16

当我从文件中读取时,我想检测空行。我试过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 !!";
    }
}

您可以这样做:

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