在C++中阅读文件时如何跳过空行?

2cmtqfgy  于 2023-01-22  发布在  其他
关注(0)|答案(3)|浏览(354)

我想在读文件时跳过空行。
我试过if(buffer ==“\n”)和if(buffer.empty()),但都不起作用。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream file_pointer;
    file_pointer.open("rules.txt", ios::in);
    if(!file_pointer.is_open())
    {
        cout << "failed to read rule file." << endl;
        return 0;
    }
    string buffer;
    while(getline(file_pointer, buffer))
    {
        if(buffer.empty())
        {
            continue;
        }
        if(buffer == "\n")
        {
            continue;
        }
        cout << buffer << endl;
    }
    file_pointer.close();
    return 0;
}
7dl7o3gd

7dl7o3gd1#

问题是“空白”行不一定是“空的”。

#include <algorithm>  // std::any_of
#include <cctype>     // std::isspace
#include <fstream>
#include <iostream>

//using namespace std;

bool is_blank( const std::string & s )
{
    return std::all_of( s.begin(), s.end(), []( unsigned char c )
    {
        return std::isspace( c );
    } );
}

int main()
{
    std::ifstream rules_file("rules.txt");
    if(!rules_file)
    {
        std::cerr << "failed to read rule file." << endl;
        return 1;
    }
    std::string line;
    while(getline(rules_file, line))
    {
        if(is_blank(line))
        {
            continue;
        }
        std::cout << line << "\n";
    }
    return 0;
}

几个音符。

  • 习惯于在标准库的东西前面写std::,用using namespace std导入所有的东西几乎总是一个坏主意。
  • C++文件流不是指针。而且,用你的名字来描述!这会让你未来的自己更容易阅读你的代码。诚实!
  • 在文件流对象创建时打开一个文件,让它在对象销毁时关闭(您已经这样做了)。
  • 将错误报告给标准错误,并通过从main()返回1来通知程序失败。
  • 将正常输出打印到标准输出,并通过从main()返回0来表示程序成功。

std::any_of()和lambdas很可能是你还没有研究过的东西,is_blank()有各种各样的写法:

bool is_blank( const std::string & s )
{
  for (char c : s)
    if (!std::isspace( (unsigned char)c ))
      return false;
  return true;
}

或者:

bool is_blank( const std::string & s )
{
  return s.find_first_not_of( " \f\n\r\t\v" ) == s.npos;
}

等等。
检查换行符不起作用的原因是getline()从输入流中删除了换行符,但没有将其存储在目标字符串中(不像fgets(),它 * 确实 * 存储了换行符,以便您知道您从用户那里得到了一整行文本)。
总的来说,你看起来有一个良好的开端。我真的建议你让自己熟悉一个好的参考,并查找你希望使用的功能。即使是现在,经过30多年的这样做,我仍然查找他们当我使用他们。
找到好东西的一种方法是在Google上输入函数的名称:“cppreference.comgetline”将带您访问ur-reference站点。

qc6wkl3g

qc6wkl3g2#

在C++中阅读文件时,可以跳过空行,方法是使用getline()函数并检查结果字符串的长度。下面是一个如何做到这一点的示例:

#include <fstream>
#include <string>

int main() {
    std::ifstream file("myfile.txt");
    std::string line;

    while (std::getline(file, line)) {
        if (line.length() == 0) {  // check if the line is empty
            continue; // skip the iteration
        }
        // process the non-empty line
    }
    file.close();
    return 0;
}

你也可以使用std::stringstream类来跳过空行,下面是一个例子:

#include <fstream>
#include <sstream>
#include <string>

int main() {
    std::ifstream file("myfile.txt");
    std::string line;

    while (std::getline(file, line)) {
        std::stringstream ss(line);
        if (ss >> line) { // check if the line is empty
            // process the non-empty line
        }
    }
    file.close();
    return 0;
}
w1e3prcc

w1e3prcc3#

**(1)**这里有一个解决方案,它将ws操作器与getline函数结合使用,以便在从流中阅读输入行时忽略前导空格。ws是一个跳过空格字符的操作器(demo)。

#include <iostream>
#include <string>

int main() 
{
  using namespace std;

  string line;
  while (getline(cin >> ws, line)) 
    cout << "got: " << line << endl;
  return 0;
}

请注意,即使该行不为空(" abc "变为"abc "),前导空格也会被删除。

**(2)**如果这是一个问题,您可以用途:

while (getline(cin, line))
  if (line.find_first_not_of(" \t") != string::npos)
    cout << "got: " << line << endl;

相关问题