Crainey
Crainey

Reputation: 1

Split a char[] and store value in different arrays C

I´m new to C programming and have a problem:

I have a string:

char input[] = "1000 10 30: 1 2 3";

I want to split input and store value in different arrays, "1000 10 30" in one array and "1 2 3" in different array.

I've tried to use strtok(), but I can´t find the solution to do it.

Somebody know how to do it?

Thanks!

Edit: Thanks, here is rest of the code:

int a1[3];
int a2[3];
char input[] = "1000 10 30:400 23 123";


char*c = strtok(input, ":");

while (c != 0)
{

    char* sep = strchr(c, ' '); 
    if (sep != 0)
    {
        *sep = 0; 
        a1[0] = atoi(c);

        ++sep;
        *sep = strtok(sep, " ");
        a1[1] = atoi(sep);

        ++sep;
        a2[2] = atoi(sep);

    }

    c = strtok(0, ":");

I used an example I found here and tried to change it to add more element to an array, but could not make it. the third element is for some reason 0, and I don't understand why. I'm a beginner++ on programming, but mostly C# and I don't used pointers before.

Upvotes: 0

Views: 77

Answers (1)

4386427
4386427

Reputation: 44329

It is unclear to me what you try to do with the pointer sep. And this code

*sep = strtok(sep, " ");

should give you compiler warnings as strtok returns a char pointer and you are trying to store it into a char (aka *sep).

You don't need more than strtok as you can give it multiple delimiters, i.e. you can give it both ' ' and ':' by passing it " :".

So the code could look like this:

int main() {
    char input[] = "1000 10 30: 1 2 3";
    int a1[3];
    int a2[3];
    int i = 0;
    char* p = strtok(input, " :");
    while(p)
    {
        if (i < 3)
        {
            a1[i] = atoi(p);
            ++i;
        }
        else if (i < 6)
        {
            a2[i-3] = atoi(p);
            ++i;
        }
        p = strtok(NULL, " :");
    }

    // Print the values
    for (int j = 0; j <i; ++j)
    {
        if (j < 3)
        {
            printf("a1[%d] = %d\n", j, a1[j]);
        }
        else if (j < 6)
        {
            printf("a2[%d] = %d\n", j-3, a2[j-3]);
        }
    }
}

Output:

a1[0] = 1000
a1[1] = 10
a1[2] = 30
a2[0] = 1
a2[1] = 2
a2[2] = 3

Tip: The above code solves the task but I recommend you take a look at sscanf as it will allow you to read the values with a single line of code.

Upvotes: 1

Related Questions