Importing data from a text file and doing something with it (Basic stuff)

This code will show the data from the .txt file "file1" the data is (0.0 0.1 0.2 0.5 0.8 0.9 1.0)
What I'm trying to do is take these float values and add them all up and divide them by 7 (finding the average and output that)
Convert it into a percent and print it in a field:
Width of 6 with 2 digits after the decimal point...
I tried doing something like cout << "the average is: " << data/7 << endl; but that didn't work. I got an error that said "/" was not an operator.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
     
    int main()
     
    {
     
     
        ifstream myfile("file1.txt");
        string data;
     
        getline (myfile, data);
        cout << data << endl;
     
     
     
        myfile.close();
     
     
        return 0;
     
    }

with
cout << "the average is: " << data/7 << endl;
your trying to divide a string by 7.

The following assumes all of the values are on the same line in the file.
I skipped reading in from a file since you already have that.
Use getline with space as the delimiter and convert each value into a float and add to the total.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string strData = "0.0 0.1 0.2 0.5 0.8 0.9 1.0";

stringstream ssData( strData );

float fTotal = 0;
int nNum = 0;
string strNum;

while( getline( ssData, strNum, _T(' ') ) )
{
  cout << strNum << endl;
  fTotal += atof( strNum.c_str() );
  nNum++;
}
	
cout << "the average is: " << setw(6) << setprecision(2) << fTotal / nNum << endl;
getline() and atof() will work, but it's more complicated than necessary.
http://www.cplusplus.com/forum/beginner/96156/#msg516162
Topic archived. No new replies allowed.