3

I have already viewed this thread but it does not account for using negative numbers if i use setfill( '0' ).

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    //Code
    int num1;

    cin >> num1;

    cout << setw(5) << setfill( '0' ) << num1 << endl;

    return 0;
}

Using this method if I enter a "5" it will display as "00005". But if I enter a -5 it will display as "000-5"

How can I fix it so that the out put will be "-0005" ?

Community
  • 1
  • 1
user3281580
  • 53
  • 1
  • 2
  • 5
  • That's why I still prefer the printf() mask format. %05d just does the right thing. – epx Feb 08 '14 at 00:55
  • @epx And once you change the type of the variable to `short` for whatever reason, your version is broken. However, since C++11 a type-safe alternative can be realized, such as [this library](https://github.com/c42f/tinyformat) – leemes Feb 08 '14 at 00:59

1 Answers1

5

The "fill character" is used to fill up the field to the specified width. By default, these characters are added to the left, such that the output will be right aligned. You can use std::left for left alignment. For numbers, the additional option std::internal will fill the space between the sign and the actual digits:

cout << setw(5) << setfill('0') << internal << -42 << endl;

http://ideone.com/Pdsz3M

leemes
  • 44,967
  • 21
  • 135
  • 183