user285372
user285372

Reputation:

Failing to read values from a file

The program below should read in a bunch of integers from a file and work out their average:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main( int argc, char** argv )
{
    ifstream fin( "mydata.txt" );
    int i, value, sum = 0;

    for ( i = 0; fin >> value; i++ )
    {
        sum += value;
    }

    if ( i > 0 )
    {
        ofstream fout( "average.txt" );
        fout << "Average: " << ( sum / i ) << endl;
    }
    else
    {
        cerr << "No list to average!" << endl;
    }

system( "PAUSE" );

}

The file mydata.txt exists in the same directory and contains 1 2 3 4 5 but the output is always: No list to average!

What am I doing wrong that it always skips the calculation and output file generation parts?

Thanks for your help,

H

Upvotes: 0

Views: 207

Answers (3)

user528298
user528298

Reputation: 16

i guess mydata.txt is not in the same directory as the executable, the code works for me

Upvotes: 0

Charles Salvia
Charles Salvia

Reputation: 53339

After you open the file, add an assert statement to make sure you've got the path correct.

ifstream fin( "mydata.txt" );
assert(fin.good());

If the assertion fails, you'll know something is probably wrong with your file path.

Upvotes: 3

Jacob
Jacob

Reputation: 34621

Try replacing mydata.txt with the absolute path

Upvotes: 1

Related Questions