setw()和setFill()不起作用...我在做什么错?
我要做的是用 double datatype 用精度2 , setW(15), 用_(underscore)填充空格和前缀 - 或 +。 >
我的代码是:
cin>>b;
if(b>0){
cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<"+"<<b<<endl;
}
else{
cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<"-"<<b<<endl;
}
我将获得的输出是: ______________+2006.01
差异:我的输出得到14个下划线
,但结果应该只有7个下划线
我尝试过的是我尝试的?
没有前缀,我的答案是准确的,因为如果我添加前缀setw(15)将我的前缀计为第15个字符,并在它之前添加14个下划线
what i am trying to do is print double datatype with precision 2,setw(15),fill spaces with _(underscore) and with prefix - or +.for example if number is 2006.008 output should be _______+2006.01
my code is :
cin>>b;
if(b>0){
cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<"+"<<b<<endl;
}
else{
cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<"-"<<b<<endl;
}
output i am getting is :
______________+2006.01
difference: my output is getting 14 underscores
but in result there should be only 7 underscores
what i tried?
without prefix my answer is accurate because if i am adding prefix setw(15) is counting my prefix as 15th character and adding 14 underscores before it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
std :: ShowPos
而不是输出字符串文字“+”
或“ - ” - “
。否则
std :: setW
设置字符串文字的字段宽度“+”
或“ - ” - “
。Use
std::showpos
instead of ouputting string literals"+"
or"-"
.Otherwise
std::setw
sets the field width for the string literals"+"
or"-"
.IO操纵器适用于流到流的单个插入。当您将
“+”
插入流中时,它的宽度为1
,其余的14
被填充_ <
/代码>因为SetFill('_'')
。如果您希望io-Anipulators应用于串联的字符串,则可以将字符串连接起来。我在这里使用弦乐流,因此您可以应用
setPrecision
和修复
:The io-manipulators apply to single insertions to the stream. When you insert
"+"
into the stream, then the width of it is1
and the remaining14
are filled with_
because ofsetfill('_')
.If you want io-manipulators to apply to concatenated strings you can concatenate the strings. I use a stringstream here, so you can apply
setprecision
andfixed
: