What error? Strtok C

Asked

Viewed 131 times

1

I made the following code that takes a string of 3 numbers separated by space, then delimits them and allocates each number in an array position, at the end it prints the array, the code works but only without the 7° and 8° lines. I’d like someone to tell me what the mistake is and teach me how to make it work even though they’ve received other values before.

#include <stdio.h>
#include <string.h>

int main()
{
    int num;
    scanf("%d", &num);
    int i = 0;
    char str[4], array[3];
    scanf ("%[^\n]", str);
    char * pch;
    fflush(stdin);
    pch = strtok(str, " ");

    while(pch != NULL)
    {
        array[i] = *pch;
        pch = strtok(NULL, " ");
        i++;
    }
    for (int i = 0; i < 3; ++i)
    {
        printf("%c ", array[i]);
    }

    return 0;
}

1 answer

0

When you make the declaration of your array to receive the number, char str[4], array[3];, you set a very small space to store 3 numbers separated by space.

When you make the entrance 1 2 3 is stored ['1',' ','2',' '], then the number 3 gets out of your string for the break;

Increase the str for str[6] that already solves your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.