将 cout 格式对齐为表格的列 [英] Align cout format as table's columns

查看:42
本文介绍了将 cout 格式对齐为表格的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于将 cout 格式对齐为表格的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆