下面的程序应该从一个文件中读入一堆整数并计算出它们的平均值:
#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" );
}
文件 mydata.txt
存在于同一目录中并且包含 1 2 3 4 5
但输出始终是:No list to average!
我做错了什么,它总是跳过计算和输出文件生成部分?
谢谢你的帮助,
H
最佳答案
打开文件后,添加 assert
语句以确保路径正确。
ifstream fin( "mydata.txt" );
assert(fin.good());
如果断言失败,您就会知道您的文件路径可能有问题。
关于c++ - 无法从文件中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4337327/