find the sum of numbers in a .txt file

i need to find the sum of rounded to one number after the dot numbers(don't know the right way to call it)(1.63 = 1.6; 3.525=3.5 etc) in a txt file located in the same folder as my project. the numbers are wtitten through enter (new line = new number). i've got something, but it doesn't work properly. could you please check and help me finish the code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include<fstream>
#include<iostream>
#include<cmath>
using namespace std;

int main()
{
    double a, sum = 0.;

    ifstream in("laura.txt");

    if (in.is_open())
    {
        while (in >> a)
        {
            sum += round(a * 10.) / 10.;
        }
        in.close();
    }
    else cout << "Unable to open file\n";

    cout << "sum=" << sum << "\n";
    
    system("pause");
    return 0;
Last edited on
Try this:

sum += static_cast<int>(round(a * 10.)) / 10.;
Try this:

still gives me sum=0
everythimg works well now, my file got erased for some reason, that's why it wasn't working
Perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
	ifstream in("laura.txt");

	if (in.is_open()) {
		long sum {};

		for (double a; in >> a; sum += lround(a * 10.0));
		cout << "sum= " << fixed << setprecision(1) << sum / 10.0 << '\n';
	} else
		cout << "Unable to open file\n";
}

Thank you!!
Topic archived. No new replies allowed.