Come posso riempire un int con zeri iniziali quando uso l'operatore cout <<?


248

Voglio coutprodurre un int con zeri iniziali, quindi il valore 1verrebbe stampato come 001e il valore 25stampato come 025. Come posso fare questo?


2
possibile duplicato di zero
— atoMerz,

Risposte:


369

Con il seguente,

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 25;
}

l'uscita sarà

00025

setfillè impostato sul carattere spazio ( ' ') per impostazione predefinita. setwimposta la larghezza del campo da stampare, e il gioco è fatto.


Se sei interessato a sapere come formattare i flussi di output in generale, ho scritto una risposta per un'altra domanda, spero che sia utile: Formattare l'output della console C ++.


3
ma .. come posso scrivere output formattato su una stringa ( char* or char[]) non per console direttamente. In realtà sto scrivendo una funzione che restituisce una stringa formattata
— shashwat il

12
@harsh use std :: stringstream
— cheshirekow

8
non dimenticare di ripristinare il formato dello stream dopo averlo fatto o otterrai una brutta sorpresa in seguito.
— Abominatore del codice

14
Questa risposta mi ha indicato la giusta direzione ma potrebbe essere migliorata. Per utilizzare effettivamente questo codice, dovrai includere <iostream>e <iomanip>nella parte superiore del tuo file e dovrai scrivere using namespace std;, ma è una cattiva pratica, quindi forse dovresti invece aggiungere il prefisso ai tre identificatori in questa risposta std::.
— David Grayson,

@shashwat puoi usare il seguente codice - std :: stringstream nomefile; filename.fill ( '0'); filename.width (5); il nome del file << std :: to_string (i);
— Prince Patel,

45

Un altro modo per raggiungere questo obiettivo è usare la vecchia printf()funzione del linguaggio C.

Puoi usare questo come

int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);

Questo verrà stampato 09 - 01 - 0001sulla console.

Puoi anche usare un'altra funzione sprintf()per scrivere output formattato in una stringa come di seguito:

int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;

Non dimenticare di includere il stdio.hfile header nel tuo programma per entrambe queste funzioni

Cosa da notare:

Puoi riempire lo spazio vuoto per 0 o per un altro carattere (non un numero).
Se scrivi qualcosa come un identificatore di %24dformato, questo non riempirà gli 2spazi vuoti. Questo imposterà il pad su 24e riempirà gli spazi vuoti.


10
So che questa è una vecchia risposta, ma va comunque sottolineato che in genere sprintf non dovrebbe essere considerato troppo attendibile poiché non è possibile specificare la lunghezza del buffer su cui dovrebbe scrivere. L'uso di snprintf tende ad essere più sicuro. L'uso di stream invece di * printf () è anche molto più sicuro dal punto di vista del tipo perché il compilatore ha la possibilità di controllare i tipi di parametri in fase di compilazione; La risposta accettata da AraK è sia di tipo sicuro sia di C ++ "standard", e non si basa su intestazioni che avvelenano lo spazio dei nomi globale.
— Magnus,

La risposta utilizza la formattazione della data come esempio. Si noti, tuttavia, che sta utilizzando un formato temporale esotico come esempio, anche se sembra simile a ISO_8601 in superficie ( en.wikipedia.org/wiki/ISO_8601 ).
— varepsilon,

32
cout.fill('*');
cout << -12345 << endl; // print default value with no field width
cout << setw(10) << -12345 << endl; // print default with field width
cout << setw(10) << left << -12345 << endl; // print left justified
cout << setw(10) << right << -12345 << endl; // print right justified
cout << setw(10) << internal << -12345 << endl; // print internally justified

Questo produce l'output:

-12345
****-12345
-12345****
****-12345
-****12345

18
cout.fill( '0' );    
cout.width( 3 );
cout << value;

ma .. come posso scrivere output formattato su una stringa ( char* or char[]) non per console direttamente. In realtà sto scrivendo una funzione che restituisce una stringa formattata
— shashwat il

2
@Shashwat Tripathi Use std::stringstream.
— AraK,

@AraK Penso che questo non funzionerebbe in Turbo C ++. L'ho usato usando sprintf(s, "%02d-%02d-%04d", dd, mm, yy);dove sè char*e dd, mm, yysono di inttipo. Questo scriverà il 02-02-1999formato in base ai valori nelle variabili.
— Shashwat,

3

Vorrei usare la seguente funzione. Non mi piace sprintf; non fa quello che voglio !!

#define hexchar(x)    ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long   Int64;

// Special printf for numbers only
// See formatting information below.
//
//    Print the number "n" in the given "base"
//    using exactly "numDigits".
//    Print +/- if signed flag "isSigned" is TRUE.
//    Use the character specified in "padchar" to pad extra characters.
//
//    Examples:
//    sprintfNum(pszBuffer, 6, 10, 6,  TRUE, ' ',   1234);  -->  " +1234"
//    sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0',   1234);  -->  "001234"
//    sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5);  -->  "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
    char *ptr = pszBuffer;

    if (!pszBuffer)
    {
        return;
    }

    char *p, buf[32];
    unsigned long long x;
    unsigned char count;

    // Prepare negative number
    if (isSigned && (n < 0))
    {
        x = -n;
    }
    else
    {
        x = n;
    }

    // Set up small string buffer
    count = (numDigits-1) - (isSigned?1:0);
    p = buf + sizeof (buf);
    *--p = '\0';

    // Force calculation of first digit
    // (to prevent zero from not printing at all!!!)
    *--p = (char)hexchar(x%base);
    x = x / base;

    // Calculate remaining digits
    while(count--)
    {
        if(x != 0)
        {
            // Calculate next digit
            *--p = (char)hexchar(x%base);
            x /= base;
        }
        else
        {
            // No more digits left, pad out to desired length
            *--p = padchar;
        }
    }

    // Apply signed notation if requested
    if (isSigned)
    {
        if (n < 0)
        {
            *--p = '-';
        }
        else if (n > 0)
        {
            *--p = '+';
        }
        else
        {
            *--p = ' ';
        }
    }

    // Print the string right-justified
    count = numDigits;
    while (count--)
    {
        *ptr++ = *p++;
    }
    return;
}

2

Un altro esempio di output di data e ora utilizzando zero come carattere di riempimento su istanze con valori a cifra singola: 2017-06-04 18:13:02

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int main()
{
    time_t t = time(0);   // Get time now
    struct tm * now = localtime(&t);
    cout.fill('0');
    cout << (now->tm_year + 1900) << '-'
        << setw(2) << (now->tm_mon + 1) << '-'
        << setw(2) << now->tm_mday << ' '
        << setw(2) << now->tm_hour << ':'
        << setw(2) << now->tm_min << ':'
        << setw(2) << now->tm_sec
        << endl;
    return 0;
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.