Needed help with c++ code

My table is not lining up right please help? write a C++ program to take numbers from an input file (input.txt), calculate the sum and average of the numbers for each row, and display them in a form of a table like this below both on screen and in a output file (output.txt). when you run my code you will see what I am trying to do. Thanks.

-0.043200 -0.003471 0.000000 0.100233
-0.040326 -0.004851 -0.000737 0.022249
-0.018204 -0.004246 -0.001530 0.161792
0.022249 0.008891 0.004870 0.199106
0.074892 0.044237 0.032171 0.341021
0.129600 0.100233 0.089016 0.221134
0.174747 0.160100 0.161792 0.003478
0.200242 0.199106 0.214417 0.012351
0.174747 0.160100 0.161792 0.032452






// prompt the user to enter the data file name
cout << "this program reads the sum and average of the values in a data file. \n" << endl;

inputFile.open("input.txt");
outputFile.open("output.txt");
Num = 1;

// Display the table
cout <<" " << " #1" << " " << "#2" << " " << "#3" << " " <<
"#4" << " " << " Sum" << " " << "Average" << endl;
cout << " --------- --------- --------- --------- --------- ---------" << endl;

while (Num <= 9)
{
inputFile >> b1 >> b2 >> b3 >> b4 >> sum >> average;
sum = b1 + b2 + b3 + b4;
average = sum/4;
cout << showpoint << fixed << setprecision(6);
cout << left << Num;
cout << setw(11) << b1 << setw(11) << b2 << setw(11) << b3 << setw(11) << b4 << setw(11) << sum <<
setw(11) << average << setw(11) << endl;
Num++;
}

cout << " --------- --------- --------- --------- --------- ---------" << endl;

inputFile.close();
outputFile.close();
return 0;
}
Last edited on
Put the alignment back to the default (right) prior to printing the floating point values.

1
2
3
4
5
6
cout << left << Num; 

cout << right ; // *** added

cout << setw(11) << b1 << setw(11) << b2 << setw(11) << b3 << setw(11) << b4 
     << setw(11) << sum << setw(11) << average << setw(11) << endl;
It helped but it didn't line up all the columns and rows. The number 1 row is lined to the left but 2-9 isn't
So do not explicitly ask for left alignment for Num

1
2
3
// cout << left << Num; 
cout << setw(5) << Num << setw(11) << b1 << setw(11) << b2 << setw(11) << b3 
     << setw(11) << b4 << setw(11) << sum << setw(11) << average << '\n' ;
Thanks that helped but the - numbers are throwing off the decimal alignment.
Topic archived. No new replies allowed.