setw()和setFill()不起作用...我在做什么错?

发布于 2025-01-27 17:24:07 字数 710 浏览 4 评论 0原文

我要做的是用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光礼记 2025-02-03 17:24:07

使用std :: ShowPos而不是输出字符串文字“+”“ - ” - “

cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<std::showpos<<b<<endl;

否则std :: setW设置字符串文字的字段宽度“+”“ - ” - “

Use std::showpos instead of ouputting string literals "+" or "-".

cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<std::showpos<<b<<endl;

Otherwise std::setw sets the field width for the string literals "+" or "-".

帅哥哥的热头脑 2025-02-03 17:24:07

IO操纵器适用于流到流的单个插入。当您将“+”插入流中时,它的宽度为1,其余的14被填充_ < /代码>因为SetFill('_'')

如果您希望io-Anipulators应用于串联的字符串,则可以将字符串连接起来。我在这里使用弦乐流,因此您可以应用setPrecision修复

if(b>0){
    std::stringstream ss;
    ss << "+" << fixed << setprecision(2) << b;
    cout << setw(15) << setfill('_') << s.str() << endl;

The io-manipulators apply to single insertions to the stream. When you insert "+" into the stream, then the width of it is 1 and the remaining 14 are filled with _ because of setfill('_').

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 and fixed:

if(b>0){
    std::stringstream ss;
    ss << "+" << fixed << setprecision(2) << b;
    cout << setw(15) << setfill('_') << s.str() << endl;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文