Reputation: 23
When I output the code on the second line of output there is a space added in that I cannot figure out how to remove. I have searched on this site and google for an answer. Sorry this is a simple fix. Would post a picture but dont have enough reputation.
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
// global constant variables
const int YEARS = 8;
const int MONTHS = 12;
const int SPACER =5;
// function prototypes
// function to read in values
void getData(double[][MONTHS], int[]);
// function to display values in table format
void printData(double[][MONTHS], int[]);
// function to print data to screen in table format using arrays
int main()
{
double rain [YEARS][MONTHS];
int years[YEARS];
/*cout << " ";*/
getData(rain, years);
printData(rain, years);
return 0;
}
// function definitions
void getData (double rainArray[][MONTHS], int yearArray[])
{
ifstream fin;
fin.open("rainfall.txt");
if (!fin)
{
cout << "Error opening file, shutting down now.\n" ;
exit(EXIT_FAILURE);
}
else
{
for( int i = 0; i < YEARS; i++)
{
fin >> yearArray[i];
for (int j = 0; j < MONTHS; j++)
{
cout << fixed << setprecision(1);
fin >> rainArray[i][j];
}
}
}
fin.close();
}
void printData (double rainArray[][MONTHS], int yearArray[])
{
for ( int i = 0; i < YEARS; i++){
cout << yearArray[i] << setw(SPACER);
for ( int j = 0; j < MONTHS; j ++)
{cout << rainArray[i][j] << setw(SPACER);
if (j == 11)
cout << endl;
}
}
}
Upvotes: 1
Views: 134
Reputation: 782785
You need to write setw()
before the field it applies to, not after.
void printData (double rainArray[][MONTHS], int yearArray[])
{
cout << fixed << setprecision(1);
for ( int i = 0; i < YEARS; i++){
cout << setw(SPACER) << yearArray[i];
for ( int j = 0; j < MONTHS; j ++)
{cout << setw(SPACER) << rainArray[i][j];
}
count << endl;
}
}
Upvotes: 1
Reputation: 4708
The setw()
calls (as with all stream manipulators) need to be before the item whose printing they're meant to affect.
cout << setw(SPACER) << yearArray[i];
You were placing them after the items, so they took effect on all lines except the first (giving the results described in the question).
Upvotes: 1