将 cout 格式对齐为表格的列

2022-01-15 00:00:00 string format c++

我很确定这是一个关于格式的简单问题,但这是我想要完成的:

I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish:

我想使用 cout 将数据输出到屏幕上.我想以表格格式输出它.我的意思是列和行应该正确对齐.示例:

I want to output data onto the screen using cout. I want to output this in the form of a table format. What I mean by this is the columns and rows should be properly aligned. Example:

Test                 1
Test2                2
Iamlongverylongblah  2
Etc                  1

我只关心单个行,所以我现在要输出的行(不工作)是

I am only concerned with the individual line so my line to output now (not working) is

cout <<var1 <<" " <<var2 <

这给了我类似的东西:

Test                 1
Test2                  2
Iamlongverylongblah         2
Etc                  1

推荐答案

setw.

#include <iostream>
#include <iomanip>
using namespace std;

int main () {
  cout << setw(21) << left << "Test"    << 1 << endl;
  cout << setw(21) << left << "Test2"   << 2 << endl;
  cout << setw(21) << left << "Iamlongverylongblah"     << 2 << endl;
  cout << setw(21) << left << "Etc"     << 1 << endl;
  return 0;
}

相关文章