Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

623
Visualizações
printf() - how to add leading zeroes + padding

I want to pad a column so it's 8 characters wide, and make integers left-aligned with at most one leading zero like this:

[00      ]
[01      ]
[07      ]
[11      ]
[14      ]

I know how to add the leading zeroes (printf("%02d\n", integer)) or the padding (printf("%-8d\n", integer)), but I don't know how to combine the two. Is there an easy way to achieve this?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Specify the minimum field width (8) and the precision (.2) and left-justification (-) — see fprintf() — like this:

#include <stdio.h>

int main(void)
{
    int array[] = { 0, 1, 7, 11, 14, 314159 };
    enum { NUM_ARRAY = sizeof(array) / sizeof(array[0]) };

    for (int i = 0; i < NUM_ARRAY; i++)
        printf("[%-8.2d]\n", array[i]);
    return 0;
}

Output (on macOS 12.3):

[00      ]
[01      ]
[07      ]
[11      ]
[14      ]
[314159  ]

This seems to be what you want.

over 4 years ago · Santiago Trujillo Relatório

0

When adding the leading zeroes and assuming that the numbers do not exceed the resulting width (in this case 2, i.e. that the integers are between -9 and 99), the width is constant so the padding can be inserted as a fixed number of spaces:

   printf("[%02d      ]\n", integer);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda