如何获取txt文件中的最后一行但不是空行

Fih*_*hop 3 c++

我想在txt文件中获取最后但不是空行.

这是我的代码:

string line1, line2;
ifstream myfile(argv[1]);
if(myfile.is_open())
{
    while( !myfile.eof() )
    {
        getline(myfile, line1);
        if( line1 != "" || line1 != "\t" || line1 != "\n" || !line1.empty() )
            line2 = line1;
    }
    myfile.close();
}
else
    cout << "Unable to open file";
Run Code Online (Sandbox Code Playgroud)

问题是我无法检查空行.

Jer*_*fin 8

好吧,让我们从明显的部分开始吧.这:while( !myfile.eof() )基本上总是错误的,所以你不会正确地检测文件的结尾.由于您正在使用getline读取数据,因此您需要检查其返回值:

while (getline(myfile, line1)) // ...
Run Code Online (Sandbox Code Playgroud)

同样,这里的逻辑:

    if( line1 != "" || line1 != "\t" || line1 != "\n" || !line1.empty() )
        line2 = line1;
Run Code Online (Sandbox Code Playgroud)

......显然是错的.我猜你真的想要&&而不是||为了这个.就目前而言,结果总是正确的,因为无论line1包含什么值,它都必须至少与这些值中的一个不相等(即,它不能同时仅包含一个制表符并且只包含一个新行并且不包含任何内容在所有 - 但这将是必要的结果是错误的).两者的测试!line1.empty()line1 != ""显得多余.


JH.*_*JH. 5

为什么不向后读取文件?这样您就不必扫描整个文件来完成此操作。好像应该是可以的。

int main(int argc, char **argv)
{
   std::cout<<"Opening "<<fn<<std::endl;
   std::fstream fin(fn.c_str(), std::ios_base::in);
   //go to end
   fin.seekg(0, std::ios_base::end);
   int currpos = fin.tellg();
   //go to 1 before end of file
   if(currpos > 0)
   {
       //collect the chars here...
       std::vector<char> chars;
       fin.seekg(currpos - 1);
       currpos = fin.tellg();
       while(currpos > 0)
       {
           char c = fin.get();
           if(!fin.good())
           {
               break;
           }
           chars.push_back(c);
           currpos -= 1;
           fin.seekg(currpos);
       }
       //do whatever u want with chars...
       //this is the reversed order
       for(std::vector<char>::size_type i = 0; i < chars.size(); ++i)
       {
           std::cout<<chars[i];
       }
       //this is the forward order...
       for(std::vector<char>::size_type i = chars.size(); i != 0; --i)
       {
           std::cout<<chars[i-1];
       }
   }
   return 0;
}
Run Code Online (Sandbox Code Playgroud)