# Thread: Seperating Digits?

1. ## Seperating Digits?

Basically is it possible to 'split' up digits from let say an integer or float.
ie. The number 741 becomes 7, 4 and 1 in 3 diff variables?

I'm not sure if there is a function to do this (since I'm relatively new to C) but any help would be great

2. First, search the forum before ask, I am sure you could have found something.
Code:
```#include <assert.h>
#include <stdio.h>
#include <malloc.h>
#include <math.h>

void fDigits(int number){
int aux = 10;
int size = 1;
int* digits;
/* counts the number of digits */
while(aux<number){
size++;
aux *= 10;
}
digits = (int*)malloc(sizeof(int)*size);
assert(digits);
aux = number;
for(int i=size;i>0;i--){
digits[i-1] = (int)(aux/pow(10, i-1));
aux -= pow(10, i-1)*digits[i-1];
}

for(int i=size-1;i>-1;i--)
printf("digit %d := %d\n", i, digits[i]);
}

int main(int argc, char** argv){
fDigits(4532);
fDigits(9);
return 0;
}```

3. Or you could use sprintf to convert the integer to a string, and then slice it to get the digits.

4. Oo okies thanks for the help guyz
I'll try a search next time as well, gustavosserra.

Btw, wuz dat code meant to compile? 'Cos I got build errors in it when I tried to compile it.

5. if you're using gcc you have to link libmath.....gcc -lm -o code code.c

6. Originally Posted by nonpuz
if you're using gcc you have to link libmath.....gcc -lm -o code code.c
Uhm... I did not know this. I use Dev, that hides this kind of thing.

7. How would I use the sprintf() function to break them up?

The format is:
Code:
` int sprintf(char *string, char *format, arg1, arg2);`
Say I have an int called input and a character array to store the 'seperated digits', how should I go about it? I dont' understand how sprintf() works :S

8. Code:
```char output[20];
int num=0xffffffff, count;
sprintf(output, "%u", num);
for (count=0; output[count]; count++)
printf("%c ", output[count]);```

Popular pages Recent additions