cstringcharintegeratoi

How to convert two characters into a string?


I've the following string saved into a char array named buffer:

{app_id:9401}

I want to obtain two integers: 94 and 01. I want to convert buffer[8] and buffer[9] into the first integer(94) and buffer[10] and buffer[11] into the second integer (1). I'm trying to do it, but I obtain segmentation fault. Why?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
{
    char buffer[] = "{app_id:9401}";

    printf("First number:%c%c. Second Number: %c%c\n", buffer[8], buffer[9], buffer[10], buffer[11]);

    char first_number[10] = "";
    strcat(first_number, buffer[8]);
    strcat(first_number, buffer[9]);

    int x = atoi(first_number);
    printf("%d\n", x);
}

Solution

  • Here is one way, by example. Scan two integers from the string, each with a maximum length of 2.

    #include <stdio.h>
    
    int main(void)
    {
        char buffer[] = "{app_id:9401}";
        int x, y;
        if(sscanf(buffer + 8, "%2d%2d", &x, &y) == 2)
            printf ("x=%d y=%d\n", x, y);
        return 0;
    }
    

    Output:

    x=94 y=1
    

    If you don't know where the number is in the string, you can find the colon with

    char *cptr = strchr(buffer, ':');