0

I have a file with data about animals, I read each line and process the information into my struct arrays but the issue is there is a space at the bottom of the animal file (and I cant simply delete it) so when I process the while loop it includes the line with the space. Any help would be great! Also my file looks like this: AnimalName:AnimalType:RegoNumber:ProblemNumber.

while (!infile.eof()) {
    getline(infile, ani[i].animalName, ':');
    getline(infile, ani[i].animalType, ':');
    getline(infile, str, ':');
    ani[i].Registration = stoi(str);
    getline(infile, str, '.');
    ani[i].Problem=stoi(str);
    cout << "Animal added: " << ani[i].Registration << " " << ani[i].animalName << endl;
    AnimalCount++;
    i++;
}
Kludo
  • 45
  • 3

1 Answers1

2

If the line contains only a single space, could you check its length (should be 1) and if it's equal to a whitespace?

If such a line is detected, simply break the loop.

#include <iostream>
#include <fstream>

int main(void) {
    std::ifstream infile("thefile.txt");
    std::string line;

    while(std::getline(infile, line)) {
        std::cout << "Line length is: " << line.length() << '\n';
        if (line.length() == 1 && line[0] == ' ') {
           std::cout << "I've detected an empty line!\n";
           break;
        }
        std::cout  << "The line says: " << line << '\n';
    }
    return 0;
}

For a test file (the second line contains one space):

hello world

end

The output is as expected:

Line length is: 11
The line says: hello world
Line length is: 1
I've detected an empty line!
markmarkmark
  • 164
  • 1
  • 6
  • 1
    Welcome here. You may consider write a little code exemple based on the OP code to illustrate your answer. – Zoma Apr 05 '19 at 07:23