Okay, after your edit, I understand you want to print the return of the function and have all digits print. While you can simply use printf()
, extracting with %
and /
is another way to extract digits. But, as you have found, when you extract digits with %
and /
, the digits will end up in reverse order. The solve that problem, you simply fill an array with digits, working from the end of the array back to the beginning.
Now before looking at a solution, if you want to "... extract the individual digits of a long data..."
-- you will need to change the type in your function from int
to long
or you will experience a mismatch of type-size on systems where int
and long
are different sizes (like on x86_64).
In order for the array to survive the return of your function, you can either pass in an array to fill using another parameter, or you can declare your array with static
storage duration so it survives return (but not that make the function not thread_safe in multithreaded programs -- not a concern here)
You can do something like the following:
#include <stdio.h>
#include <stdlib.h>
#define NCHR 32 /* if you need a constant, #define one (or more) */
#define BASE 10
char *extract_digits (long n)
{
static char digits[NCHR]; /* static, so digits survives return */
char *p = digits + NCHR - 1; /* pointer to last char in digits */
int sign = n < 0; /* check sign of n (negative, sign == 1) */
if (sign) /* process positive number */
n = -n;
if (!n) { /* handle zero case, sign irrelevant */
*--p = '0';
return p;
}
do { /* convert each digit to char */
*--p = n % BASE + '0'; /* fill from end of digits array */
n /= BASE;
} while (n);
if (sign) /* if sign, add '-' at front */
*--p = '-';
return p; /* return ptr to start of digits in digits[] */
}
int main (int argc, char **argv) {
long v = argc > 1 ? strtol(argv[1], NULL, BASE) : -2381;
printf ("digits: %s
", extract_digits(v));
}
(note: I have change the function name to extract_digits()
, you can rename it as you please)
The program prints the extracted digits directly using the function return -- which is what I take was your intent from the question.
Example Use/Output
Using default value:
$ ./bin/extractdigits_fnc
digits: -2381
Passing value:
$ ./bin/extractdigits_fnc 54823
digits: 54823
Passing zero:
$ ./bin/extractdigits_fnc 0
digits: 0
Passing negative zero:
$ ./bin/extractdigits_fnc -0
digits: 0
Your '16' example:
$ ./bin/extractdigits_fnc 16
digits: 16
Look things over and let me know if I understood your question correctly.