计算C ++中文件的平均值

问题描述 投票:0回答:1

我必须计算文件中保存的数字的平均值,但是会收到“ +”运算符错误。有什么问题吗?

int main()
{
    int a;
    fstream File;
    string Line;
    File.open("file.txt", ios::in);
    if (File.is_open()){
    while(!File.eof()) //.eof -> End Of File
    {
        File>>Line;
        a=a+Line;
        cout<<Line<<"\n";
        cout << a;
    }
    }
    else{
        cout << "File open error";
    }
    File.close();
    return 0;
}
c++ file average
1个回答
1
投票

您不能将字符串添加到int。首先读取一个int,而不是一个字符串。

您也根本不像您的问题所要求的那样计算平均值。您仅在计算总和。

尝试以下方法:

int main() {
    ifstream File("file.txt");
    if (File.is_open()) {
        int num, count = 0, sum = 0;
        while (File >> num) {
            ++count;
            sum += num;
        }
        if (File.eof()) {
            cout << "count: " << count << endl;
            cout << "sum: " << sum << endl;
            if (count != 0) {
                int average = sum / count;
                cout << "average: " << average << endl;
            }
        }
        else {
            cerr << "File read error" << endl;
        }
    }
    else {
        cerr << "File open error" << endl;
    }
    return 0;
}

Live Demo

© www.soinside.com 2019 - 2024. All rights reserved.