Lining columns up

Solved!

This is what I wrote:

cout << setw(4) << "Students";
cout << setw(20) << "Hours Worked";
cout << setw(20) << "of Total Hours";
cout << endl;

for (int i = 0; i < students; i++)
{
    cout << setw(20);
    cout << names[i];
    cout << setw(10) << hours[i];
    cout << setw(10) << percent[i];
    cout << endl;
}

But if the first name is a few characters sorter or bigger than second name, they become misaligned. How would I keep each column aligned equally?

Answers


Try something like this:

#include<iostream>
#include <iomanip>   
#include<string>

using namespace std;


int main()
{
  int students = 5;
  string names[5] = {"a","bccc","c","d","ecsdfsdfasdasasf"};
  int hours[5] = {1,2,3,4,5};
  int percent[5] = {10,20,30,40,54};

  string column("Students");

  int maxStringSize = 0;
  int sizeOfStudentColumn = column.length();

  for(int i = 0; i < 5; ++i)
  {
    if(maxStringSize < names[i].length())
     maxStringSize = names[i].length();
  }

  if(sizeOfStudentColumn > maxStringSize)
    maxStringSize = sizeOfStudentColumn;

  cout<<"max size: "<<maxStringSize<<endl;

  cout << setw(4) << "Students";
  cout << setw(maxStringSize + 5) << "Hours Worked";
  cout << setw(20) << "of Total Hours";
  cout << endl;

  for (int i = 0; i < students; i++)
  {
//    cout << setw(20);
    cout << names[i];
    int diff = maxStringSize - names[i].length();
    cout << setw(diff + 5 ) << hours[i];
    cout << setw(20) << percent[i];
    cout << endl;
  }
}

Need Your Help

Cannot read property ScheduleDate from undefined

javascript

var AppPatientsList = JSON.parse(JSON RESPONSE);

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.