1

I've got a bit of code that I am trying to get to work. Basically I want to open a file and print the contents to the terminal. Right now I've just got a list (1-10) in a .txt file in the same folder as my .cpp file.

int main() {
  ifstream inFile;    
  inFile.open("numbers.txt");

  if( inFile.fail()) {    
    cout<<"Error opening file "<< endl;    
    return 0;
  }

  while(!(inFile.fail())) {
    int x;
    inFile >> x;
    cout<<x<< endl;
  }
}

This is what I have so far and it works to open the file and print to the console. Only issue is, that it prints the last line of the file twice ( so it print 1-10 fine but prints 10 twice) I've stumped myself trying to figure this out. Any ideas?

Thanks for helping me edit this!

Elchapo
  • 59
  • 1
  • 12

1 Answers1

5

Try below code

#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ifstream inFile;
  inFile.open("a.txt");

  if( inFile.fail()) {
    cout<<"Error opening file "<< endl;
    return 0;
  }

  int x;
  while(inFile >> x) {
    cout<<x<< endl;
  }
}
Manthan Tilva
  • 2,656
  • 2
  • 14
  • 32