C++ 将 cout 格式与表格的列对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/275484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:15:32  来源:igfitidea点击:

Align cout format as table's columns

c++stringformat

提问by BobS

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

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

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:

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

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 << "\t\t" << var2 << endl;

cout << var1 << "\t\t" << var2 << endl;

Which gives me something like:

这给了我类似的东西:

Test                 1
Test2                  2
Iamlongverylongblah         2
Etc                  1

回答by Eugene Yokota

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

回答by Leon Timmermans

I advise using Boost Format. Use something like this:

我建议使用Boost Format。使用这样的东西:

cout << format("%|1| %2%") % var1 % var2;

回答by Leon Timmermans

You must find the length of the longest string in the first column. Then you need to output each string in the first column in a field with the length being that of that longest string. This necessarily means you can't write anything until you've read each and every string.

您必须在第一列中找到最长字符串的长度。然后您需要输出字段中第一列中的每个字符串,其长度为该最长字符串的长度。这必然意味着在您阅读每个字符串之前您不能写任何东西。

回答by avishayhajbi

you can do it with

你可以用

string str = "somthing";
printf ("%10s",str);
printf ("%10s\n",str);
printf ("%10s",str);
printf ("%10s\n",str);