-
How can I take a number, like 23167 and then be able to seperate between the ones,tens,hundreds,ect, digits. So I could end up having something like
a1 = 7; // ones digit
a2 = 6; // tens digit
a3 = 1; // hundreds digit
a4 = 3; // thousands digit
a5 = 2; //ten-thousand digit
Thanks
-
First you need to convert it to a string -- either a real string, or just a simple char* array:
Code:
char buf[40];
itoa(number, buf, 10);
Then you can access it as buf[0], buf[1], etc.
-
Or if you didn't want to waste time creating a string (I mean execution time), you could just use the mod operator ( % ) to get the remainder after dividing by 10, that would give you the units. To get tens, divide by 10 then mod 10. To get 100s, divide by 100 then mode 10. You could use a function like this:
PHP Code:
int getDigit(int iPosition, int iNumber, int iRadix)
{
for(int i=0; i<iPosition; i++)
iNumber /= iRadix;
return(iNumber % iRadix);
}
posotion 0 is the units, 1 is tens, 2 is hundreds, etc.
-
Oh I should say that iRadix should be ten if you're counting in decimal :rolleyes: It will (or should I think) work for hex or binary or octal or whatever else you might want if you pass a different radix in.
-
Thanks to both of you, I couldn't get itoa to work, but HarryW's way worked.
-
itoa converts a number to a string so that it can be printed, reversed, etc. It's actually very similar to Harry's method.
Code:
char* itoa(char *buf, int number, int radix);