C++桌库特和约马尼普

C++ table cout and iomanip

本文关键字:马尼普 C++      更新时间:2023-10-16

我的程序中有一个小的对齐问题。

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    cout << setw(5) << "Sl. No:" << setw(15) << "Month" << setw(15) << "Name" << endl << endl;
    cout << setw(5) << 1 << setw(15) << "January" << setw(15) << "Abhilash" << endl;
    cout << setw(5) << 2 << setw(15) << "Februaury" << setw(15) << "Anandan" << endl;
    cout << setw(5) << 3 << setw(15) << "March" << setw(15) << "Abhilash" << endl;
    cout << setw(5) << 4 << setw(15) << "April" << setw(15) << "Anandan" << endl;
    return 0;
}

在我得到的输出中,月份的名称不正确。

Sl. No:          Month           Name
    1        January       Abhilash
    2      Februaury        Anandan
    3          March       Abhilash
    4          April        Anandan

似乎有什么问题?

字符串Sl. No:宽为 7,您正在尝试将其放入 5 宽的列中。这会将第一行推上 2 列。尝试将第一列设为 7 宽而不是 5 宽:

cout << setw(7) << "Sl. No:" << setw(15) << "Month" << setw(15) << "Name"
     << endl << endl;
cout << setw(7) << 1 << setw(15) << "January" << setw(15) << "Abhilash"
     << endl;
//...

当你想使用 setw 时,你必须从输出字符串、int 等的末尾计数。 所以当你说

 cout << setw(15) << "January";

它将格式化 8 个空格,因为 1 月是 7 个字符。所以在你的例子中,你想有

 cout << setw(23) << "January";

这显然取决于您是否将第一个输出"1"保留在同一位置。

您也可以

setw()之前使用"\t",以确保您不会占用空间。

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    cout << setw(5) << "Sl. No:" << setw(15) << "Month" << setw(15) << "Name" << endl << endl;
    cout << setw(5) << 1 << "t" << setw(15) << "January" << "t" << setw(15) << "Abhilash" << endl;
    cout << setw(5) << 2 << "t" << setw(15) << "Februaury" << "t" << setw(15) << "Anandan" << endl;
    cout << setw(5) << 3 << "t" << setw(15) << "March" << "t" << setw(15) << "Abhilash" << endl;
    cout << setw(5) << 4 << "t" << setw(15) << "April" << "t" << setw(15) << "Anandan" << endl;
    return 0;
}
哦,

你需要在"月"前面使用间距

    "  month"

    "month"

结果将如下所示

     Month
    January

您可能需要调整使用的间距量。