Search code examples
cstringsocketsrecv

How to process recv return


I´m getting a string like this from C socket recv function and would like ideas how to process it and get numeric values that comes beside the letters(S,L,E...) on the string

S@AB@L1550 @W
>E0578A9069C0000
>S0223W0418
>R2219H1429S0000
>G0156V0116T1800
>m0138
>m0087

For example letter, need to get the numeric 223 and the same to others;

Was thinking to do a loop and read all vector and checking the key words. But not sure if has some way easier or faster


Solution

  • This code demonstrates one way to do the job.

    /* SO 4635-2633 */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)
    {
        char data[] =
            "S@AB@L1550 @W\n"
            ">E0578A9069C0000\n"
            ">S0223W0418\n"
            ">R2219H1429S0000\n"
            ">G0156V0116T1800\n"
            ">m0138\n"
            ">m0087";
        const char digits[] = "0123456789";
    
        printf("Raw data:\n[%s]\n", data);
    
        size_t offset = 0;
        size_t skip;
        //for (skip = strcspn(data + offset, digits);
        //     data[skip] != '\0';
        //     skip = strcspn(data + offset, digits)) 
        while (data[(skip = strcspn(data + offset, digits))] != '\0')
        {
            size_t len = strspn(data + offset + skip, digits);
            if (len == 0)
                break;
            char numstr[32];
            memmove(numstr, data + offset + skip, len);
            numstr[len] = '\0';
            int number = atoi(numstr);
            printf("Number %4d (position %2zu..%-2zu - [%.*s])\n",
                   number, offset + skip, offset + skip + len - 1,
                   (int)len, data + offset + skip);
            offset += skip + len;
        }
    
        return 0;
    }
    

    When run, the output is:

    Raw data:
    [S@AB@L1550 @W
    >E0578A9069C0000
    >S0223W0418
    >R2219H1429S0000
    >G0156V0116T1800
    >m0138
    >m0087]
    Number 1550 (position  6..9  - [1550])
    Number  578 (position 16..19 - [0578])
    Number 9069 (position 21..24 - [9069])
    Number    0 (position 26..29 - [0000])
    Number  223 (position 33..36 - [0223])
    Number  418 (position 38..41 - [0418])
    Number 2219 (position 45..48 - [2219])
    Number 1429 (position 50..53 - [1429])
    Number    0 (position 55..58 - [0000])
    Number  156 (position 62..65 - [0156])
    Number  116 (position 67..70 - [0116])
    Number 1800 (position 72..75 - [1800])
    Number  138 (position 79..82 - [0138])
    Number   87 (position 86..89 - [0087])
    

    You can use the for loop in place of the while loop at the cost of duplicating the call to strcspn(). I preferred not to repeat myself.