[英]How does the setw stream manipulator work?
我想知道, setw
流操纵器(空间计数)如何工作? 例如,当有 1 个\t
时,我想用四个空格打印a
,所以我使用\t
并将\t
与setw
进行比较。
我写的代码:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t"<<"a\n";
std::cout<<std::setw(9)<<"a\n";
return 0;
}
输出:
a // This is 1 '\t'
a // This is setw()
所以我的想法是:
setw(18)
= \t\t
听起来合乎逻辑吧? 但是当我尝试这段代码时:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a";
return 0;
}
它给了我这个输出:
a
a
怎么了?
那是因为您需要在setw(18)
添加一个\n
。 这适用于任何setw
。
示例代码:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a\n"; // And you add the \n here
return 0;
}
输出:
a
a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.