Convert char[] to int

I am trying to convert a character array to an int.

For example, the character array (with 4 slots) would be:   U003

and I want to change that to an int (not an int[]) of 003
groovy998Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Infinity08Connect With a Mentor Commented:
Note that you can still use atoi or strtol by skipping the U character :

        char str[] = "U003";
        int val = atoi(str + 1);                  /* <--- val will now contain 3 */
        int val2 = strtol(str + 1, 0, 10);    /* <--- val2 will now contain 3 */
0
 
Infinity08Commented:
Usually, you'd use either atoi or strtol

        char str[] = "1234";
        int val = atoi(str);                  /* <--- val will now contain 1234 */
        int val2 = strtol(str, 0, 10);    /* <--- val2 will now contain 1234 */

Reference pages :

        http://www.cplusplus.com/reference/clibrary/cstdlib/atoi.html
        http://www.cplusplus.com/reference/clibrary/cstdlib/strtol.html


However, since your string starts with a U character, you can use sscanf :

        char str[] = "U003";
        int val = 0;
        sscanf(str, "U%d", &val);        /* <--- val will now contain 3 */

Reference page :

        http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html
0
All Courses

From novice to tech pro — start learning today.