-1

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;
}
Taco
  • 23
  • 5
  • 5
    `Line` is a string. You cannot add a `int a` to a string. Convert string to a number first with `stoi()`, `stof()` etc. depending upon your use-case. – Roy2511 Apr 29 '20 at 08:39
  • Oh of course, thanks – Taco Apr 29 '20 at 08:40
  • 2
    [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – molbdnilo Apr 29 '20 at 08:52
  • 2
    @Roy2511 or, just replace the string with an int instead. `>>` can read directly into an int, you don't need to do it manually – Remy Lebeau Apr 29 '20 at 09:45
  • @RemyLebeau sure, why not. – Roy2511 May 04 '20 at 08:11

1 Answers1

2

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

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620