开发者

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 开发者_如何学Cthe 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


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.


Try replacing mydata.txt with the absolute path


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜