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

Which plugin do you use for SVN in Visual Studio?

visual-studio svn version-control visualsvn ankhsvn

I'm considering using SVN for my .Net projects, and I'd like to know what plugins are available for integrating the source control capabilities directly into the Visual Studio IDE.