0

I am having trouble with the file input.

#include <iostream> 
#include <vector>
#include <fstream>

using namespace std;

int main (int argc, char *argv[]) {
ifstream my_file(argv[1]);

cout << argv[1] << endl;

  int input;
  vector<int> w;

  while(!my_file.eof()) {

     my_file >> input;
     cout << "current input: " << input << endl;
     w.push_back(input);
  }
   
  return 0;

}

my data file is "input1.dat" which is

2 3 4 1 2 1 3 5 4 3 

But, what I get the output(w) is

2 3 4 1 2 1 3 5 4 3 3 

Why there is one more 3 at the last? Loop supposed to be end as while loop reach the end of file.

coco_code
  • 1
  • 2
  • `*.eof()` is not true after you've read the last numbers, its only once you try to read again and reach the end of the file, that it becomes true. – Mansoor May 13 '21 at 12:59
  • After you read your input, you don't check if it was successful before using the value. – Galik May 13 '21 at 13:00
  • Replace `while(!my_file.eof()) { my_file >> input;` with `while (my_file >> input) {` to fix the extra number at eof problem. – drescherjm May 13 '21 at 13:03

0 Answers0