C ++从文件中加载数字然后找到总和

C++ loading numbers from a file then finding the sum

我昨晚发布了一些关于此的内容,但我决定稍微改变一下我的方法,因为我没有完全理解我尝试使用的代码。

我很抱歉,因为我知道这个话题已经结束了,但我希望对我编写的代码有一点帮助。

我正在从我的计算机加载一个包含 100 个整数的 .txt 文件。它们每个都在新行上。

到目前为止,这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

int main ()
{
    ifstream fout;
    ifstream fin;



    string line;
    ifstream myfile ("100intergers.txt");
    if (myfile.is_open())
    {
        while ( getline(myfile,line) )
        {
            cout << line << '\n';
        }

        // Closes my file
        myfile.close();


        // If my file is still open, then show closing error
    if (myfile.is_open())
        cerr << "Error closing file" << endl;
        exit(1);
    }


    int y = 0;
    int z = 0;
    int sum = 0;
    double avg = 0.0;

    avg = sum/(y+z);
    cout << endl << endl;
    cout << "sum = " << sum << endl;
    cout << "average = " << avg << endl;

    // checking for error
    if (!myfile.eof())
    {
        cerr << "Error reading file" << endl;
        exit(2);
    }

    // close file stream "myfile"
    myfile.close();

    return(0);

}

当我 运行 它时,我得到退出代码 1(以及我的 100 个整数的列表)。

这意味着我的 if 子句不是正确的选择,什么是更好的选择?

如果我完全删除该位,它无法 运行 计算错误,我认为是 0/0*0

此外,我认为我为 .txt 文件编写的代码是针对单词而非数字的,但是当我将字符串更改为 int 时,它确实会出错,并告诉我我遇到的问题比没有遇到的要多。

最后 - 在这之后我想制作一个数组来计算方差 - 有什么提示吗?

干杯

杰克

您正在从您输出的文件中读取行。

然后你对一些变量进行算术运算,所有这些变量的值为零。
这些变量与文件内容无关。

我将通过展示一种计算文件中数字的方法来帮助了解基本循环结构:

int main()
{
    int value = 0;
    int count = 0;
    ifstream myfile("100intergers.txt");
    while (myfile >> value)
    {
        count++;
    }
    cout << "There were " << count << " numbers." << endl;
}

总结一下,剩下的留作练习。