What error? strtok C

1

I made the following code that receives a string of 3 numbers separated by space, then delimits them and allocates each number in an array position, in the end it prints the array, the code works however only without the 7th and 8th ° rows. I would like someone to tell me what the error was and to teach me how to make it work even by getting other values first.

#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;
}
    
asked by anonymous 03.11.2017 / 22:33

1 answer

0

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

When input 1 2 3 is stored ['1',' ','2',' '] , then number 3 is left out of its string for breaking;

Increase str to str[6] that already solves your problem.

    
03.11.2017 / 22:50