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.
-
2\$\begingroup\$ Mandatory don't use namespace std, based on a hunch that you are. \$\endgroup\$Yann– Yann2014年10月28日 09:51:27 +00:00Commented Oct 28, 2014 at 9:51
2 Answers 2
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])))
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.
-
\$\begingroup\$ You don't need that lambda. The conversion from
char
toint
is implicit, so you should be able to usestd::isspace
directly as the predicate. \$\endgroup\$glampert– glampert2014年10月28日 16:39:14 +00:00Commented Oct 28, 2014 at 16:39