Search code examples
cstringscanfdelimiter

C - Separating string using other delimiters?


I have a string in the format "B1,B3,B4,B6" and would like to assign each number to a variable i.e. num1 = "1", num2 = "3", num3 = "4", and num4 = "6". Is this implementation of sscanf valid?

char *num1;
char *num2;
char *num3;
char *num4;
sscanf(str, "B%s,B%s,B%s,B%s", num1, num2, num3, num4);

Solution

  • No that's not really a good way. If you just want the numbers a numbers, i.e. as normal int values, then use the "%d" conversion operator instead, and have your variables be normal int variables, which you then pass to sscanf using the address-of operator &. As in

    int num1;
    int num2;
    int num3;
    int num4;
    sscanf(str, "B%d,B%d,B%d,B%d", &num1, &num2, &num3, &num4);
    

    If you on the other hand want the digits as strings, then use array instead of pointers:

    char num1[2];  // Two characters is enough for a single-character string, plus terminator
    char num2[2];
    char num3[2];
    char num4[2];
    sscanf(str, "B%1s,B%1s,B%1s,B%1s", num1, num2, num3, num4);
    

    The format "%1s" tells sscanf to only read a signle character.


    Besides that, you should probably make sure that the sscanf call actually parsed the input correctly. This can be done by checking what sscanf returns:

    if (sscanf(str, "B%d,B%d,B%d,B%d", &num1, &num2, &num3, &num4) == 4)
    {
        // All okay
    }
    else
    {
        // Something went wrong
    }