Hi... I'm trying to write a program that reads data(numbers) from a text file into an array, finds the average and sorts it in ascending order then outputs the result into a txt file. Here's what I've done so far... it's not running, pls help

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


int main ()
{

float gradeData[12]; //creates array to hold names
//short count1; //for loop for input
float count;//holds data read from the rainfall.txt file per line
float holdData;
ifstream myfile ("rainfall.txt");  


cout<<"Opening file ::: Filename ::: grades.txt";
if (myfile.is_open())   
{
        while (! myfile.eof() ) //while the end of file is NOT reached
        {
            getFloat (myfile,holdData); //get one line from the file
            gradeData[count] = holdData;
            cout<<gradeData[count]<< endl; //and output it
            count++;
        }
        myfile.close(); //closing the file
    }
    else cout<<"Error ::: Unable to open file"; //if the file is not open output
         
    system("pause");
    return 0;
}

Everything is supposed to be in functions.... I don't know where to start.... if you don't want to give the full answer no problem.... if I see some examples I should be fine. I'll really really appreciate the help.... Yes the code is not complete... don't know how to proceed.

Recommended Answers

All 6 Replies

The easiest way to read the numbers into an array is like this:

float gradeData[12] = {0.0F};
int i; // loop counter
ifstream myfile ("rainfall.txt");
if( myfile.is_open() )
{
    i = 0;
    while( i < 12 && myfile >> gradeData[i] )
            i++;
}

The easiest way to read the numbers into an array is like this:

float gradeData[12] = {0.0F};
int i; // loop counter
ifstream myfile ("rainfall.txt");
if( myfile.is_open() )
{
    i = 0;
    while( i < 12 && myfile >> gradeData[i] )
            i++;
}

Thanks so much.... how would I find the average of the numbers read from the txt file....

Thanks so much.... how would I find the average of the numbers read from the txt file.... Posted in the wrong place I guess.... also to output the result to a txt file.....
Thanks

1) Simple 4th grade (probably) math. Just add up all the values in the array and divide by the total number of values.

2) use cout to display then one at a time inside a loop.

Exactly how to write the code for the above is up to you. The solution to 2) is only one like of code.

Ok... thanks... I'll work on it and see what happens... thanks so much.. you've been amazing...

Sorry, one more thing... if I was to call the read txt file from a function... how will I do it.... any example(even though not exact would be fine...)?

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.