如何让我的打印像桌子一样?

时间:2016-05-06 16:35:46

标签: c++ tabular

我打印出以下代码:

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

看起来像这样

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

我该怎么做才能做到这一点:

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

1 个答案:

答案 0 :(得分:4)

Set field width std::setw正是您要找的。

用法示例:

#include <iostream>     // std::cout, std::endl
#include <iomanip>      // std::setw

int main () {
  std::cout << std::setw(10) << "test" << std::endl; 
  return 0;
}

由于参数为10,因此std::setw将在屏幕的第10,11,12,13个字符上显示"test"

在您的情况下,您将使用与此类似的例程,并且通过一些试验和错误,您将实现您想要的目标:

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