0

How can I convert an integer to a string in C and include a leading zero if the integer has only one digit? The result is needed to print to an LCD Display and not to print to console.

#include <stdio.h>
#include <stdlib.h>

int main ()
{
    int i = 7;
    char buffer[10];
    itoa(buffer, i, 10);
    printf ("decimal: %s\n",buffer);
    return 0;
}

This code would print 7 but i need it to be 07. But numbers greater than 10 eg.: 77 should remain the same.

Daniel
  • 308
  • 2
  • 14
  • You need to add a conditional if statement that detects if the integer being parsed is less than "10", and greater than 0, I assume. – Monstarules Dec 03 '20 at 19:27
  • Does this answer your question? [Printing leading 0's in C?](https://stackoverflow.com/questions/153890/printing-leading-0s-in-c) – kaylum Dec 03 '20 at 19:27
  • @kaylum he is asking about a string, not an integer conversion. – Monstarules Dec 03 '20 at 19:27
  • The reference post uses `printf` to print to stdout. If you want it to a buffer use `snprintf` but the format string is the same. – kaylum Dec 03 '20 at 19:27
  • I need the string to send it to an LCD Display as descriped above. I don't want to print it to console i only do this for testing. – Daniel Dec 03 '20 at 19:29
  • `snprintf(buffer, sizeof(buffer), "%02d", i)` – kaylum Dec 03 '20 at 19:30
  • 1
    Using `sprintf` or `snprintf` doesn't require printing to any output device. It writes to the *same* string that you use in the `itoa` call. – Adrian Mole Dec 03 '20 at 19:31
  • @AdrianMole I didn't know that, thanks then I'll test that – Daniel Dec 03 '20 at 19:32
  • you have to check integer input before convert it into string and if integer is smaller than 10 use strcat to concat 0 to your string number ? – mohammadmahdi Talachi Dec 03 '20 at 19:34

1 Answers1

2

Instead of itoa, you can use the sprintf function with a format specifier of %02d to force the inclusion of a leading zero:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i = 7;
    char buffer[10];
//  itoa(buffer, i, 10);
    sprintf(buffer, "%02d", i);
    printf("decimal: %s\n", buffer);
    return 0;
}
Adrian Mole
  • 43,040
  • 110
  • 45
  • 72