Captain_Tiras Captain_Tiras - 1 year ago 112
C++ Question

std::getline doesn't skip empty lines when reading from ifstream

Consider this code:

vector<string> parse(char* _config) {
ifstream my_file(_config);
vector<string> my_lines;
string nextLine;
while (std::getline(my_file, nextLine)) {
if (nextLine[0] == '#' || nextLine.empty() || nextLine == "") continue;
return my_lines;

and this config file:

#Verbal OFF

#Highest numeric value

67D 44D 54D 63D AS 69H 100D 41H 100C 39H 10H 85H 7D 42S 6C 67H 61D 33D 28H 93S QH 5D 91C 40S 50C 74S 8C 98C 96C 71D 82S 75S 23D 40C 29S QC 84C 16C 80D 13H 35S

P1 1
P2 2

My goal is to parse the config file to a vector of strings, parsed line by line, ignoring empty lines and the '#' character.

When running this code on Visual Studio, the output is correct But, when running on Linux with g++, I still get some empty lines.

Answer Source

Your input file most likely has lines ending with CR LF, i.e. Windows/DOS text files. Linux expects all lines ending with LF only, so on Linux, std::getline() ends up reading a line containing a single CR character.

Before the existing code that checks the contents of nextLine, check if the line is non-empty, and ends with the CR character, then remove it. Then continue on with your existing if statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download