#1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2002
    Location
    Seattle WA
    Posts
    863
    Rep Power
    14

    String to integer


    I'm coding a windows application, and I need to read a string and convert it to an integer.

    Currently, I'm currently using _ttoi, which works as expected for a raw decimal integer. Now, what if I want to be able to use hex codes and such? Is there a function that can take a string like '0x32' and return the number 50?

    Coding it by hand would be easy, I just figure there's got to be some kind of pre-written one out there.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    Hehe, I was about to code a similar function just now for my own project, when suddenly I remembered a function from a long time ago. :) It's called sscanf(). It works the same as scanf() except that it uses a string for its first argument and a format string for the second argument (sort of like sprintf()). If you want, here's some code I tried out:

    Code:
    #include <stdio.h>
    int main() {
      char *foo = "F00";
      int x;
    
      sscanf(foo, "%X", &x);
      printf("Hex %s is dec %d", foo, x);
      return 0;
    }
    Hope this helps!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2002
    Location
    Seattle WA
    Posts
    863
    Rep Power
    14
    Beautiful. Using a %i formatting string does exactly what I wanted it to do: the user can enter either decimal or hexidecimal and the function will sort it out accordingly.

    Thanks!

IMN logo majestic logo threadwatch logo seochat tools logo