Member Avatar for PolarPear

Hello,

I've checked google now intermidintly for two days, and I could not find a solution for my problem, so I decided I would post my own thread on here.

The program I'm designing is supposed to ask the user for a file name, open that file, then take the average and find the least and greatest. My problem is, my program is getting stuck just accepting data from a file, and I'm not sure why. It never even gets to any of my functions.

Here's some of my code:

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

void Average(double NumbersFromFile[50], int);
void Least(double NumbersFromFile[50], int);
void Greatest(double NumbersFromFile[50], int);

int main()
{
    int Counter=0;
    double NumbersFromFile[50]={0};
    char FileName[50]={0};

    cout << "What is the name of you file?" << endl;
    cin >> FileName;

    ifstream InputFile;
    InputFile.open(FileName);
	
     if(InputFile)
    {
	cout << "Error!";
	return 0;
    }
	
    
    while(!InputFile.eof())
     {	

        InputFile >> NumbersFromFile[Counter];
        Counter++;
     }

	
    InputFile.close();

    Least(NumbersFromFile, Counter);
    Greatest(NumbersFromFile, Counter);
    Average(NumbersFromFile, Counter);

    return 0;


}

Any help would be greatly appreciated.

Modify your code with,

if(!InputFile)
    {
	cout << "Error!";
	return 0;
    }

What happen if value count exceed 50?

while(!InputFile.eof())
     {	
        InputFile >> NumbersFromFile[Counter];
        Counter++;
       if(Counter==50)
            break;
     }
Member Avatar for PolarPear

Adatapost,

That is great advice about adding the break for my while loop, I should have had it for robustness in the first place.

I suppose I still have a follow up question though. Any file name I enter, it breaks now, because it doesn't open the file correctly.

I don't know what I am doing wrong for it not to open the file correctly though.

Member Avatar for PolarPear

Once again, I appreciate your help. From the computer science books I have, the input file part of my code should be exactly right.

I have created an output file, just to check to see if that would work, and it works fine. My input file on the other hand, even if I write the name of the file into my code instead of having it be user entered, still does not open.

I'm not sure what I'm doing different between the two.

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.