gpt4 book ai didi

c++ - 将 cout 格式对齐为表格的列

转载 作者:IT老高 更新时间:2023-10-28 12:44:51 25 4
gpt4 key购买 nike

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

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

Test                 1
Test2 2
Iamlongverylongblah 2
Etc 1

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

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

这给了我类似的东西:

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

关于c++ - 将 cout 格式对齐为表格的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/275484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com