Home > other >  How to skip blank line when reading file in C ?
How to skip blank line when reading file in C ?

Time:01-20

I want to skip blank line when readhing a file.

I've tried if(buffer == "\n") and if(buffer.empty()), but it not work. I did like this:

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

CodePudding user response:

The problem is that a “blank” line need not be “empty”.

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

A few notes.

  • Get used to writing std:: infront of things from the Standard Library. Importing everything en masse with using namespace std is almost always a bad idea.
  • C file streams are not pointers. Moreover, be descriptive with your names! It makes reading your code easier for your future self. Honest!
  • Open a file at the file stream object creation. Let it close at object destruction (which you did).
  • Report errors to standard error and signal program failure by returning 1 from main().
  • Print normal output to standard output and signal program success by returing 0 from main().

It is likely that std::any_of() and lambdas are probably not something you have studied yet. There are all kinds of ways that is_blank() could have been written:

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

Or:

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

Etc.

The reason that the checking for newline didn’t work is that getline() removes the newline character(s) from the input stream but does not store it/them in the target string. (Unlike fgets(), which does store the newline so that you know that you got an entire line of text from the user.) C is much more convenient in this respect.

Overall, you look to be off to a good start. I really recommend you make yourself familiar with a good reference and look up the functions you wish to use. Even now, after 30 years of this, I still look them up when I use them.

One way to find good stuff is to just type the name of the function in at Google: “cppreference.com getline” will take you to the ur-reference site.

CodePudding user response:

You can skip blank lines when reading a file in C by using the getline() function and checking the length of the resulting string. Here is an example of how you can do this:

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

You can also use the std::stringstream class to skip blank lines, here is an example:

#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;
}
  •  Tags:  
  • c
  • Related