Trouble reading from a file in dev c++

I have written up a c++ program that will read from a file. The file consists of only numbers ( from 1 to 50) and spaces with no other special characters. The main aim of the program is to tell me how many times the numbers appeared in the file but whenever i run my program it always hangs. Any help is appreciated.


#include <iostream>
#include <fstream>
using namespace std;

int main()
{
int num;
int A[50];
ifstream infile;

for (int i = 0; i < 50; i++)
A[i] = 0;

infile.open("Numbers.txt");

infile >> num;

while (!infile.eof())
{

for (int j = 0; j < 50; j++)
{
if (num == j)
A[j] = A[j] + 1;
}


infile >> num;
}

for (int k = 0; k < 50 ; k++)
cout << k <<" appeared " <<A[k] << " times " << endl;
}
Don't loop on eof(). If the stream goes into a different state (such as fail() or bad()) you won't catch it. Your loop should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
ifstream infile("Numbers.txt");    // no need to call open(), you can just use the constructor

while(infile >> num)    // operator>>() returns a reference to the stream
{
	for(int i = 0; i < 50; ++i)
	{
		if(num == i + 1)    /* you said the file contains numbers from 1 to 50;
			               remember that arrays are numbered from 0 */
		{
			++A[i];
		}
	}
}
Topic archived. No new replies allowed.