Hello again guys!
i have a simple question how to promt user to enter a number for example 444 or whatever and for c to print it as a 9 digit number, so if its 444 c would print it as 000000444?

any help would be greatly appriciated.,

thanx!

Dani AI

Generated

and already gave the quick formatting approaches, and 's example just prints a literal "9" before the number. For production code you usually want safer input handling and explicit control over sign, validation, and buffer sizes. The snippet below reads a line, verifies the characters are digits (optionally with a leading minus), and builds a 9-digit, zero-padded string you can reuse or print.

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

int main(void) {
    char in[64];
    if (!fgets(in, sizeof in, stdin)) return 1;
    size_t len = strlen(in);
    if (len && in[len-1] == '\n') in[--len] = '\0';

    int neg = (in[0] == '-');
    char *digits = neg ? in + 1 : in;
    if (*digits == '\0') return 1; /* no digits */

    for (char *p = digits; *p; ++p)
        if (!isdigit((unsigned char)*p)) return 1; /* invalid input */

    size_t dlen = strlen(digits);
    if (dlen >= 9) { puts(in); return 0; } /* choose how to handle long input */

    char out[12]; /* sign + 9 digits + NUL fits */
    char *o = out;
    if (neg) *o++ = '-';
    memset(o, '0', 9 - dlen);
    o += 9 - dlen;
    memcpy(o, digits, dlen);
    o[dlen] = '\0';
    puts(out);
    return 0;
}

Notes and gotchas:

  • Decide policy for inputs longer than 9 digits (print as-is, truncate, or error).
  • Use fgets instead of scanf to avoid partial reads and buffer overruns.
  • This pads digits after a minus sign; adjust if you want a different behavior.
  • Leading zeros are presentation only; they do not change the stored numeric value.

Recommended Answers

All 4 Replies

Do you want to do it just so you could justify it to the right? If so you could use this:

int i=444;
printf("%9d",i);

It won't include any zeroes at the beginning but it'll be right justified.

int n = 444;
printf("%09d", n);

More examples here.

commented: %09d- ofcourse! *whacks self* +1

Thanx a lot guys!

int i=444;
printf("9%d",i);

commented: Eh? +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.