2
\$\begingroup\$

In reading a file, I found blank lines (even at the bottom) crash the program. To fix this, I've added the following if statement:

string line;
while(getline(inFile, line))
{
    if(line.length() < 1 || (line.length() == 1 && isspace(line.at(0))))//this was added
        continue;
    string result = process(line);
    aStruct.field1 = result;
    //...rest of code
}

For what it's worth, it can be assumed there isn't going to be a bizarre mix of white space making an entire line. For example, one line isn't going to be six spaces (maybe one space, by mistake). This solution isn't exactly elegant.

\$\endgroup\$
4
\$\begingroup\$

The at() method validates that the input is in the correct range. Since you have already done the validation there is no point in using this method you may as well use operator[]

Additionally there is a call to check for empty strings empty() so prfer to use that rather than test the length against zero.

if (line.empty() || (line.length() == 1 && isspace(line[0])))
\$\endgroup\$
0
\$\begingroup\$

For what it's worth, it can be assumed there isn't going to be a bizarre mix of white space making an entire line. For example, one line isn't going to be six spaces (maybe one space, by mistake). This solution isn't exactly elegant.

If you do assume there can be lines with multiple spaces (or if it makes no difference), you can write this:

auto is_space = [](char c) { return isspace(c); };

string line;
while(getline(inFile, line))
{
    // if(line.length() < 1 || (line.length() == 1 && isspace(line.at(0))))
    if(all_of(begin(line), end(line), is_space))
        continue;
    string result = process(line);
    aStruct.field1 = result;
    //...rest of code
}

This way, you no longer need to check the length at all.

\$\endgroup\$
  • \$\begingroup\$ You don't need that lambda. The conversion from char to int is implicit, so you should be able to use std::isspace directly as the predicate. \$\endgroup\$ – glampert Oct 28 '14 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.