C 表对齐 - cout 和 iomanip

新手上路,请多包涵

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

 #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

似乎是什么问题?

原文由 Babbzzz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 406
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;
}

原文由 maiankeith 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏