c++formattingnumber-formattingcoutsetw

setw() and setfill() not working...what am i doing wrong?


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


Solution

  • 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;