user1234567
user1234567

Reputation: 4311

EOF suddenly reaching with getline() in ifstream

I have file "in.txt" which consist of 2 strings:

abcde
12345

I have my code:

#include <iostream>
#include <fstream>
int main() {
   std::ifstream fileIn("in.txt", std::ios::in);

   char* chPtr = new(char[10]);
   char ch;

   printf("fileIn.get()==EOF?: %d \n", (fileIn.get() == EOF));  // =0
   std::cout << "fileIn.eof() = " << fileIn.eof() << "\n";  // =0

   fileIn.getline(chPtr, 3);
   std::cout << "chPtr-" << chPtr << "\n";  //output:"bc" (see 1.)
   fileIn.get(ch);
   std::cout << "ch-" << ch << "\n";   //(see 2.)

   printf("fileIn.get()==EOF?: %d \n", (fileIn.get() == EOF));  // =1 (see 3.)
   std::cout << "fileIn.eof() = " << fileIn.eof() << "\n";  // =0 (see 4.)

   fileIn.close();
   delete[] chPtr;  
}

Remarks to code:

(1.) 1st symbol 'a' was eaten by get() slightly above; Thus 2 next symbols read here, and 3rd symbol, what i wanted to read, getline() automatically assigns with value '\0' (if I understand correctly).

(2.)And here are is the question - here outputs symbol (with code [-52]). Unfortunately I haven't enough reputation to post images =( (This symbol is like 2 vertical white lines, right line of this pair is with gap at the middle). (for information: I got this symbol each time, I'm trying to read to char variable an uninitialized element of char-array.) But why I get it there?? Because there are still unreaded symbols in 1st string & whole 2nd string!

(3.) It turns out that, the cursor suddenly moved to the end of file. But WHY?? I can't understand

(4.) We still have zero here, because (if I understand correctly) there was not attempt of reading data behind the eof-line. The cursor just moved to place behind the last symbol of file, but not out of the file-end-border).

Upvotes: 1

Views: 243

Answers (1)

jrok
jrok

Reputation: 55395

If istream::getline manages to read count-1 characters (count is 3 in your example) before EOF is reached, it will set failbit. See the reference.

This means all further extractions will fail unless you clear the flag, not that "cursor moved to the end". ch never gets initialized.

Upvotes: 1

Related Questions