Search code examples
c++tabular

How can I make my print out like a table?


I have the following code to print out:

cout<<current->bookId<<"\t\t"<<current->bookName<<"\t\t"<<current->year<<"\t\t";
cout<<"Checked out by student "<<current->storedBy<<endl;

It looks like this

BookId          BookName                Year            Status
1000            Machine Learning                1997            Checked out by student 21000000
1200            Data Mining             1991            Checked out by student 21000020
1400            C++ How to Program              2005            Checked out by student 21000020
1500            Pattern Recognition             2000            Checked out by student 21000000

What should I do to make it like that:

BookId          BookName                        Year            Status
1000            Machine Learning                1997            Checked out by student 21000000
1200            Data Mining                     1991            Checked out by student 21000020
1400            C++ How to Program              2005            Checked out by student 21000020
1500            Pattern Recognition             2000            Checked out by student 21000000

Solution

  • Set field width std::setw is what you are looking for.

    Usage example:

    #include <iostream>     // std::cout, std::endl
    #include <iomanip>      // std::setw
    
    int main () {
      std::cout << std::setw(10) << "test" << std::endl; 
      return 0;
    }
    

    Since the parameter is 10, so the std::setw will display "test" on the 10th, 11th, 12th, 13th characters of the screen.

    In your case, you would use a routine similar to this, and with some trials and errors you will achieve what you want:

    std::cout << std::setw(10) << "col1" << std::setw(5) << "col2" << std::endl;