Tabular Format

Can someone help me to understand what I have done wrong? I am getting input from the user on Last Name, First Name and GPA. When my data outputs, my data aligns properly in the table for Last Name and First Name but my GPA data output does not align correctly under the GPA table heading. Assistance is greatly appreciated.

#include <iostream>

#include <string>

#include <algorithm>

#include <iomanip>



using namespace std;

struct student

{

string firstName;

string lastName;

double GPA;

};



int main()

{

student pupil1;

student pupil2;

student pupil3;

student pupil4;

student pupil5;

student pupil6;

student pupil7;

student pupil8;

student pupil9;

student pupil10;



int i;

int j;



cout << "Please enter student's name (Last/First): ";

cin >> pupil1.firstName >> pupil1.lastName;

pupil1.firstName[0] = toupper(pupil1.firstName[0]);

pupil1.lastName[0] = toupper(pupil1.lastName[0]);



cout << "Please enter student's GPA: ";

cin >> pupil1.GPA;



int numPupils = 9;

student pupils[10];

int maxLastName = 0;

int maxFirstName = 0;

for (i = 0; i < numPupils; i++) {

cout << "Please enter student's name (Last/First): ";

cin >> pupils[i].firstName >> pupils[i].lastName;



pupils[i].firstName[0] = toupper(pupils[i].firstName[0]);

maxFirstName = std::max(maxFirstName, (int)pupils[i].firstName.length());



pupils[i].lastName[0] = toupper(pupils[i].lastName[0]);

maxLastName = std::max(maxLastName, (int)pupils[i].lastName.length());



cout << "Please enter student's GPA: ";

cin >> pupils[i].GPA;

}




string column2 = "Last Name";

string column1 = "First Name";

string column0 = "GPA";



maxFirstName = max(maxFirstName, (int)column1.length());



cout << endl;

cout << column1;

for (i = column1.length(); i < maxFirstName; i++) cout << " ";

cout << " "; // space between columns

cout << column2;

cout << " "; // space between columns

cout << column0;

cout << " "; // space between columns

cout << endl;



for (i = 0; i < numPupils; i++) {

cout << pupils[i].firstName;

for (j = pupils[i].firstName.length(); j < maxFirstName; j++) cout << " ";

cout << " "; // space between columns

cout << pupils[i].lastName;

cout << " "; // space between columns

cout << pupils[i].GPA;

cout << " "; // space between columns

cout << endl;

}
}

This is not an easy task, to get it perfect you need to count the longest string on each column, and add enough spaces between each string to make them the same amount of characters. Then it may not be correct depending on the font used and how the font is rendered, in which case adding a tab character "\t" may help to line it up.
Last edited on
Topic archived. No new replies allowed.