Search code examples
c++setw

Lining columns up


Solved!

enter image description here

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?


Solution

  • 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;
      }
    }