Rebecca Tucker Rebecca Tucker - 4 months ago 20
C Question

Splitting a string into elements of a struct

I have a struct defined as below

struct gtid{
int id1;
int id2;
int num;
}


How can I convert a string in the form "1-2-3" and initialize the struct accordingly that is

gtid -> id1 = 1;
gtid -> id2 = 2;
gtid -> num = 3;


Or How can I cast the string into the appropriate struct.

Answer

You can read formatted values from stdin with scanf function and from string with sscanf function. See the complete example below.

#include  <stdio.h>

typedef struct {
    int id1;
    int id2;
    int num;
} gtid_t;

int main(void) {
    gtid_t gtid;

    // read from stdin
    scanf("%d-%d-%d", &(gtid.id1), &(gtid.id2), &(gtid.num));
    printf("id1 = %d, id2 = %d, num = %d\n", gtid.id1, gtid.id2, gtid.num);

    // read from string
    char* str = "4-5-6";
    sscanf(str, "%d-%d-%d", &(gtid.id1), &(gtid.id2), &(gtid.num));
    printf("id1 = %d, id2 = %d, num = %d\n", gtid.id1, gtid.id2, gtid.num);

    return 0;
}

Output would be as follows

id1 = 1, id2 = 2, num = 3
id1 = 4, id2 = 5, num = 6