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.