C++中std::setw()的用法
std::setw(n)的作用是设置输出宽度为n,默认为右对齐,并且用空格填充。
例如:cout << std::setw(5) << "0" << "1" << endl,该语句就是设置字符串"0"的输出宽度为5,默认为右对齐,空格填充。
若想使用其他符号填充(例如用'*'填充),则可以用cout << std::setw(5) << setfill('*') << "0" << "1" << endl;
如果想修改成左对齐,则只需要在std::setw(n)之前加上std::left即可。
当要输出的字符串宽度大于setw设置的宽度n时,直接输出想要输出的字符串即可(此时忽视setw设置的宽度)。
通过运行如下测试代码即可了解setw()的规则:
#include <iomanip>
#include <iostream>
#include<string.h>
using namespace std;int main()
{/*默认为右对齐,此时加不加std::right都可以 */cout << std::setw(5) << "0" << "1" << endl;cout << std::setw(5) << "00" << "1" << endl;cout << std::setw(5) << "000" << "1" << endl;/*用<<left或者std::left改成左对齐*/cout << std::left << std::setw(5) << "0" << "1" << endl;cout << std::left << std::setw(5) << "00" << "1" << endl;cout << std::left << std::setw(5) << "000" << "1" << endl;/*当要输出的字符串宽度大于setw设置的宽度时,直接输出想要输出的字符串即可*/cout << std::right <<std::setw(5) << "0000000" << "1" << endl;/*用其他符号填充*/cout << std::right <<std::setw(5) << setfill('*') << "0" << "1" << endl;cout << std::left << std::setw(5) << setfill('*') << "0" << "1" << endl;return 0;
}
代码运行结果:
C++中std::setw()的用法相关推荐
- C++中std::string::find_last_of用法
早上本来还看代码时本来还迷迷糊糊,结果被find_last_of一下给震醒了,std::string 使用了这么多年,今天才发现find_last_of只是用来查找字符的,多年来一直以为它可用来查找字 ...
- 【C++】浮点数的std::fixed、std::setprecision()、std::setw()用法
[C++]50.浮点数的std::fixed.std::setprecision().std::setw()用法 C++中std::setw()的用法 1. std::fixed() #include ...
- C++/C++11中std::string用法汇总
C++/C++11中std::string是个模板类,它是一个标准库.使用string类型必须首先包含<string>头文件.作为标准库的一部分,string定义在命名空间std中. st ...
- C++中std::tr1::function和bind 组件的使用
在C++的TR1中(Technology Report)中包含一个function模板类和bind模板函数,使用它们可以实现类似函数指针的功能,但却却比函数指针更加灵活,特别是函数指向类的非静态成员函 ...
- 概率论中指数分布介绍及C++11中std::exponential_distribution的使用
指数分布:在深度学习中,我们经常会需要一个在x=0点处取得边界点(sharp point)的分布.为了实现这一目的,我们可以使用指数分布(exponential distribution): p(x; ...
- 概率论中高斯分布(正态分布)介绍及C++11中std::normal_distribution的使用
高斯分布:最常用的分布是正态分布(normal distribution),也称为高斯分布(Gaussian distribution): 正态分布N(x;μ,σ2)呈现经典的"钟形曲线&q ...
- 概率论中伯努利分布(bernoulli distribution)介绍及C++11中std::bernoulli_distribution的使用
Bernoulli分布(Bernoulli distribution):是单个二值随机变量的分布.它由单个参数ø∈[0,1],ø给出了随机变量等于1的概率.它具有如下的一些性质: P(x=1)= ø ...
- C++11 std::bind std::function 高级用法
C++11 std::bind std::function 高级用法 (c++11的新特性) 原文:https://blog.csdn.net/yangjie6898862/article/detai ...
- C++中substr函数的用法
C++中substr函数的用法 #include<string> #include<iostream> using namespace std; main() { string ...
最新文章
- Qt Creator添加资源
- 算法-----------计算二叉树的最大深度
- Vue+axios 实现http拦截及vue-router拦截
- ●BZOJ 4596 [Shoi2016]黑暗前的幻想乡
- 14-python基础3-数据类型
- linux awk 某一列合并,利用shell中awk和xargs以及sed将多行多列文本中某一列合并成一行...
- js产生页面内的顺序序列号
- laravel 5.2 异常处理页面
- c语言数组指针定义方法,C语言数组指针定义方法
- php中阿里云快递物流查询接口使用
- AgileCDN加速情况数据测评
- Snipaste截图软件的下载和使用(日常常用的一些功能)
- esp8266 安信可AiThinkerIDE_V1.5.2开发环境搭建
- c语言写按键控制蜂鸣器,单片机按键控制蜂鸣器演奏音乐
- CSS基础教程 -- 媒体查询屏幕适配
- 0xC00000FD: Stack overflow
- 袋鼠云数据中台专栏(一) :浅析数据中台策略与建设实践
- Java基础知识——BIO模式
- 为什么使用计算机辅助翻译工具中文译文,TCloud计算机辅助翻译工具
- 我国路内限时长停车管理可行性研究