Question

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" ?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top