0

I am wondering why my file input doesn't work when I use getline(). I tried temp to get rid of spaces, but that did work either.

void getKittenFromFile(string file, roster& kitt) {
  string temp;
  ifstream inFS;
  int i = kitt.size;
  inFS.open(file);
  if (!inFS.is_open()) {
    cout << "Error! File not found." << endl;
  }
  else {
    while (!inFS.eof() && kitt.size < 10) {
      getline(inFS, kitt.kittens[i].name);
      getline(inFS, kitt.kittens[i].color);
      inFS >> kitt.kittens[i].score;
      i++;
      kitt.size++;
    }

The file looks like this:

Willow
dark brown
66
jack
brown
84
Will
blue
6
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • 4
    `inFS >> kitt.kittens[i].score;` This leaves a newline in the buffer which the next `getline()` reads as a blank line. [Mixing ifstream getline and >>](//stackoverflow.com/q/9336209) – Johnny Mopp Feb 11 '20 at 23:23
  • 3
    One possible factor: [`while (!inFS.eof() ...`](https://stackoverflow.com/q/5605125/10077). – Fred Larson Feb 11 '20 at 23:23
  • 1
    is `kitt.size == 0` when the function is called? Is `kitt.kittens` a plain array (with place for 10 elements)? – Ted Lyngmo Feb 11 '20 at 23:26
  • 1
    [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/) – Remy Lebeau Feb 12 '20 at 00:20
  • IMHO, you should place the input method with the structure. This reduces the need for the outside world to know the data members inside the `class` or `struct`. – Thomas Matthews Feb 12 '20 at 00:39

1 Answers1

0

As mentioned by one of the comments, you have a trailing '\n' getting caught by your getline() as a result of reading using >>. To solve this, you could use get() to clear out a single newline character or, a more complete solution would be to use: inFS.ignore(numeric_limits<streamsize>::max(), '\n');

arc-menace
  • 373
  • 3
  • 13