C++PrimerPlus(第6版)中文版:Chapter6_sumafile

本文档展示了如何使用C++实现一个简单的程序,它从用户输入的文件中读取数据,计算总和并求平均值,适用于基础文件操作和数学计算的教学或实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// Chapter6_sumafile.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <fstream>
#include <cstdlib>
const int SIZE = 60;


int main()
{
    std::cout << "Hello World!\n";
    using namespace std;
    char filename[SIZE]; 
    ifstream inFile;//OBJECT for handing file input
    cout << "Enter name of data file:";
    cin.getline(filename,SIZE);
    inFile.open(filename);//associate inFile with a file;
    if (!inFile.is_open())//fail to open file
    {
        cout << "Could not open the file" << filename << endl;
        cout << "Program terminating.\n";
        exit(EXIT_FAILURE);
    }
    double value;
    double sum = 0.0;
    int count = 0;// numbers of items read

    inFile >> value;//get first value
    while (inFile.good())//while input good and not at EOF
    {
        ++count;//one more items read
        sum += value;//caculate
        inFile >> value;//get next value
    }
    if (inFile.eof())
        cout << "End of file reached.\n";
    else if (inFile.fail())
        cout << "Input terminated by data mismatch.\n";
    else
        cout << "Input terminated for unknown reazon.\n";
    if (count == 0)
        cout << "No data processed.\n";
    else
    {
        cout << "Items read:" << count << endl;
        cout << "Sum:" << sum << endl;
        cout << "Average:" << sum / count << endl;

    }
    inFile.close();
    return 0;

       



}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值