|
-
Feb 25th, 2001, 05:05 PM
#1
Thread Starter
Lively Member
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
-
Feb 25th, 2001, 05:55 PM
#2
Monday Morning Lunatic
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.
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Feb 25th, 2001, 06:36 PM
#3
Frenzied Member
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.
Harry.
"From one thing, know ten thousand things."
-
Feb 25th, 2001, 06:40 PM
#4
Frenzied Member
Oh I should say that iRadix should be ten if you're counting in decimal 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.
Harry.
"From one thing, know ten thousand things."
-
Feb 25th, 2001, 09:12 PM
#5
Thread Starter
Lively Member
Thanks to both of you, I couldn't get itoa to work, but HarryW's way worked.
-
Feb 26th, 2001, 07:47 AM
#6
Monday Morning Lunatic
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);
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|