Results 1 to 6 of 6

Thread: Is there a mid$

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 1999
    Posts
    89
    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

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    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

  3. #3
    Frenzied Member HarryW's Avatar
    Join Date
    Jan 2000
    Location
    Heiho no michi
    Posts
    1,827
    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 iPositionint iNumberint iRadix)
    {
         for(
    int i=0i<iPositioni++)
              
    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."

  4. #4
    Frenzied Member HarryW's Avatar
    Join Date
    Jan 2000
    Location
    Heiho no michi
    Posts
    1,827
    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."

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Aug 1999
    Posts
    89
    Thanks to both of you, I couldn't get itoa to work, but HarryW's way worked.

  6. #6
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    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
  •  



Click Here to Expand Forum to Full Width