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
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
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]; } printf("Received: %d\n", number); 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; }
Nothing more to tell about me...
Happy day =)
Or you could use sprintf to convert the integer to a string, and then slice it to get the digits.
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.
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.Originally Posted by nonpuz
Nothing more to tell about me...
Happy day =)
How would I use the sprintf() function to break them up?
The format is:
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 :SCode:int sprintf(char *string, char *format, arg1, arg2);
Code:char output[20]; int num=0xffffffff, count; sprintf(output, "%u", num); for (count=0; output[count]; count++) printf("%c ", output[count]);