How to find average from each column ?

I have a file that contains rows and columns

2456 128 234 67
2368 200 249 70
2655 212 250 89

I need to find the average for each column. This is what I try :

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
string input;
ifstream namefile("payment.txt");

if (!namefile)
return (cout << " ERROR : cannot open file.\n"), 1;
while (getline(namefile, input))
cout << input << endl;

namefile.clear();
namefile.seekg(0);

int a {}, b {}, c {}, d {};
namefile >> a >> b >> c >> d >> e;

int price1 = a;
int price2 = b;
int price3 = c;
int price4 = d;

for (a = 0; a < 3 ; a++)
{
int total = a ;
a++;
price1 = a/3;
}

std::cout << "The average price for A is " << price1 << '\n';
}


I try to run this coding but it did not works. Does anyone know how to make it work? Please help me



Hello Hyung,

While I work on understanding what you have done.


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



Andy
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

You have a compile error.
Line 21: e is undefines

Why are you trying to read 5 values? You have 4 columns in your data.

Line 21: You only read the first line of data.

Lines 28-33: What's the point of your for loop? You're doing the same computations 3 times. Are you expecting a different result?
Why are you incrementing a twice each time through the loop? You won't execute the loop the correct number of times.

It's a poor idea to reuse a as your loop variable. a is value of your first column.

Have you learned to arrays yet?


Hello Hyung,

Before I change 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>

#include <fstream>

using namespace std;  // <--- Best not to use.

int main()
{
    string input;
    ifstream namefile("payment.txt");

    if (!namefile)
    {
        return (cout << " ERROR : cannot open file.\n"), 1;
    }

    while (getline(namefile, input))
    {
        cout << input << endl;
    }

    namefile.clear();
    namefile.seekg(0);

    int a{}, b{}, c{}, d{}, total{};

    // <--- Next line would work better in a while loop.
    namefile >> a >> b >> c >> d /*>> e*/;  // <--- "e" not defined or needed. Only reads 1 line of the file.

    int price1 = a;  // <--- Do not know what you indended, but not the way to do this.
    int price2 = b;
    int price3 = c;
    int price4 = d;

    for (a = 0; a < 3; a++)  // <--- This for loop is not necessary. Can be done in the while loop.
    {
        int total = a;  // <--- Never used in the for loop. Also local to the loop and not available after the loop ends.
        a++;
        price1 = a / 3;  // <--- Can be calculated in the next "cout" statement.
    }

    std::cout << "The average price for A is " << price1 << '\n';  // <--- "price1" would be better as "total.

    return 0;  // <--- Not required, but makes a good break point for testing.
}


Andy
Simply, consider:

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
26
27
28
29
30
31
#include <fstream>
#include <iostream>

constexpr size_t nocols {4};

std::ifstream& operator>>(std::ifstream& ifs, int cols[nocols]) {
	for (size_t c = 0; c < nocols; ++c)
		ifs >> cols[c];

	return ifs;
}

int main()
{
	std::ifstream ifs("Payment.txt");

	if (!ifs)
		return (std::cout << "Cannot open file\n"), 1;

	int sum[nocols] {};
	size_t rows {};

	for (int col[nocols]; ifs >> col; ++rows)
		for (size_t c = 0; c < nocols; ++c)
			sum[c] += col[c];

	std::cout << "The column averages are:\n";

	for (size_t c = 0; c < nocols; ++c)
		std::cout << "Column " << c + 1 << ": " << (sum[c] + 0.0) / rows << '\n';
}



The column averages are:
Column 1: 2493
Column 2: 180
Column 3: 244.333
Column 4: 75.3333

Hello Hyung,

You are doing way to much work in your code and as mentioned some of it does not work. "a", "b", "c" and "d" are great for column names, but terrible as variable names.

Have a look at this:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>
#include <string>

#include <fstream>

using namespace std;  // <--- Best not to use.

int main()
{
    const std::string inFileName{ "payment.txt" };  // <--- Put File name here.

    std::ifstream inFile(inFileName);

    if (!inFile)
    {
        return std::cerr << "\n     File " << std::quoted(inFileName) << " did not open.\n", 1;  // <--- Requires header file "<iomanip>".
        //return std::cerr << "\n     File \"" << inFileName << "\" did not open.\n", 1;
    }

    int lineCount{};
    string input;
 
    std::cout << std::fixed << std::setprecision(2);  // <--- Only needs done once.

    std::cout <<
        "\n A   B   C   D\n"
        "---------------\n";

    while (getline(inFile, input))
    {
        cout << input << '\n';

        lineCount++;
    }

    inFile.clear();
    inFile.seekg(0);

    int colA{}, colB{}, colC{}, colD{};
    double total{};

    // <--- Next line would work better in colA while loop.
    while (inFile >> colA >> colB >> colC >> colD)
    {
        total += colA;
    }

    std::cout << "\nThe average price for A is " << total / lineCount << '\n';

    return 0;  // <--- Not required, but makes a good break point for testing.
}

The advantage to using "lineCount" is if your file has more than 3 lines you will divide by the correct number of rows. "lineCount" is a suggestion. "numRows" came to mind after I started with "lineCount". Either one will work.

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


int main()
{
   const int COLS = 4;
// ifstream in( "payment.txt" );
   istringstream in( "2456 128 234 67\n"
                     "2368 200 249 70\n"
                     "2655 212 250 89\n" );

   int n = 0;
   valarray<double> sumav( 0.0, COLS );
   for ( double a, b, c, d; in >> a >> b >> c >> d; n++ ) sumav += valarray<double>{ a, b, c, d };
   sumav /= n;
   cout << "The column averages are: ";
   for ( double e : sumav ) cout << e << " ";
}


The column averages are: 2493 180 244.333 75.3333 
Topic archived. No new replies allowed.