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 = 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;
}

Welcome to DaniWeb!

Please use code tags when posting code, it makes it much more readable for us.

This question seems to appear over and over again. Maybe someone can make example here: http://programmingexamples.net/index.php?title=CPP#I.2FO of "correctly" reading a file one character at a time as well as one line at a time. I think this would get heavily re-used.

To actually count the characters, you should use: http://programmingexamples.net/index.php?title=CPP/Strings/CountCharacters

Thanks,

Dave

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.