C++中改变setw(n)的对齐方式

 

转自 : http://www.cnblogs.com/wxxweb/archive/2011/06/01/2065671.html

使用setw(n)设置输出宽度时,默认为右对齐,如下:

// include <iostream>
// include <iomanip>
std::cout << std::setw(5) << "1"    << std::endl;
std::cout << std::setw(5) << "10"   << std::endl;
std::cout << std::setw(5) << "100"  << std::endl;
std::cout << std::setw(5) << "1000" << std::endl;

//
// 输出结果:
//
//     1
//    10
//   100
//  1000
//

若想让它左对齐的话,只需要插入 std::left,如下:

// include <iostream>
// include <iomanip>
std::cout << std::left << std::setw(5) << "1"    << std::endl;
std::cout << std::left << std::setw(5) << "10"   << std::endl;
std::cout << std::left << std::setw(5) << "100"  << std::endl;
std::cout << std::left << std::setw(5) << "1000" << std::endl;
// 输出结果:
//
// 1
// 10
// 100
// 1000
//

同理,右对齐只要插入 std::right,不过右对齐是默认状态,不必显式声明。

原文链接: https://www.cnblogs.com/javaexam2/archive/2012/03/17/2632849.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++中改变setw(n)的对齐方式

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/44413

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午9:02
下一篇 2023年2月8日 下午9:03

相关推荐