Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ouput an integer with positive sign and zeros preceding it

Tags:

c++

I want a number to be displayed with a positive sign and three 0's preceding it, but what I am getting so far is 000+1 when what I want is +0001

    #include <iostream>
    #include <iomanip>

    using namespace std;

    int main(void)
    {
        int number = 1;

        cout << showpos;
        cout << setfill('0') << setw(5) << number << endl;
    }
like image 980
jacobay43 Avatar asked Mar 04 '23 05:03

jacobay43


2 Answers

You need to also set std::internal flag. This way you will get your expected +0001 - test at ideone.

like image 118
Freddie Chopin Avatar answered Apr 07 '23 02:04

Freddie Chopin


This is what the std::internal manipulator is for. For example,

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

prints "-0005" instead of "000-5" as without std::internal.

like image 20
Nadav Har'El Avatar answered Apr 07 '23 01:04

Nadav Har'El