How to read from file in c++

myFirstfile.txt has 4 numbers 4 5 6 7. I am not getting any output. Instead I am getting blinking cursor. I want the numbers from file as output. Please help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
int x, neg=0, pos =0,sum=0;	
ifstream myfile;
myfile.open("firstFile.txt");
    
while (! myfile.eof() )	
{
myfile>>x;
cout<<x<<endl;
}
myfile.close();
return 0;	
}
Last edited on
Don't loop on EOF. Use proper indentation.

I don't know why you aren't seeing any output from that code, though.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iomanip>
#include <iostream>

int main()
{
  int x;
  int count = 0;
  ifstream f( "firstFile.txt" );
  while (f >> x)
  {
    count++;
    cout << x << "\n";
  }
}

Hope this helps.
Thanks. got it.
Topic archived. No new replies allowed.