Chris
Chris

Reputation: 89

convert char array into int 2d array in C language

I have a char array of indefinite number of "couples" composed by index and value, separated by semicolon. Each index is separated from its value by a comma.

Example:

char srt[50] = "1,3; 2,4; 0,-2; 3,11";   

("index1, value1; index2, value2; ...")

I want to convert the char array into a 2d int array, like this:

int num[4][2] = {{1,3}, {2,4}, {0,-2}, {3,11}};

How?

Upvotes: 1

Views: 631

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

Hoping not to get downvoted for doing you homework, but I just found some time to code something. The approach is to first count the (possible) number of pairs (which is the number of semicolons + 1) in order to reserve a proper array. Then, use a loop with strtok to separate the pairs and a sscanf(str, "%d,%d",..) to read in the values. Note that the actual number of pairs might be different from the maximum number of pairs due to failures on parsing a pair:

int main()
{
    char srt[50] = "1,3; 2,4; 0,-2; 3,11";

    char* p=srt;
    size_t pairsCount = 1;
    while (*p) {
        if (*p++ == ';')
            pairsCount++;
    }

    int pairs[pairsCount][2];

    p = strtok(srt, ";");
    pairsCount = 0;
    while (p) {
        int key = 0, value = 0;
        if (sscanf(p, "%d,%d", &key, &value) == 2) {
            pairs[pairsCount][0] = key;
            pairs[pairsCount][1] = value;
            pairsCount++;
        }
        p = strtok(NULL, ";");
    }

    for (int i=0; i<pairsCount; i++) {
        printf("%d,%d\n", pairs[i][0], pairs[i][1]);
    }

    return 0;
}

Upvotes: 1

Related Questions