Click to See Complete Forum and Search --> : Is there a mid$
Allanon
Feb 25th, 2001, 04:05 PM
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
parksie
Feb 25th, 2001, 04:55 PM
First you need to convert it to a string -- either a real string, or just a simple char* array:
char buf[40];
itoa(number, buf, 10);
Then you can access it as buf[0], buf[1], etc.
HarryW
Feb 25th, 2001, 05:36 PM
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:
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.
HarryW
Feb 25th, 2001, 05:40 PM
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.
Allanon
Feb 25th, 2001, 08:12 PM
Thanks to both of you, I couldn't get itoa to work, but HarryW's way worked.
parksie
Feb 26th, 2001, 06:47 AM
itoa converts a number to a string so that it can be printed, reversed, etc. It's actually very similar to Harry's method.
char* itoa(char *buf, int number, int radix);
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.