简体   繁体   中英

Counting the average numbers from a file in C++

I have to calculate the average of the numbers saved in the file, but I get the "+" operator error. What's the problem?

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;
}

You can't add a string to an int. Read into an int to begin with, not into a string.

You are also not calculating an average at all, like your question asks for. You are only calculating a sum.

Try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM