Splitting string in C

2

I'm very new to C, but I have a lot of experience with python, I have a project that I need to get 3 numbers on the same line and make a vector with these 3 numbers

in the input digit

3 1 37

I wanted you to form a vector [3,1,37] there is only one thing, the first one (in this case 3) can also be characters. something like

load 1 23 or delete 2 56

In python it would be extremely simple, it was just getting an input string and dps making an input = input.split ()

#include <stdio.h>
#include <string.h>C
int main ()
{
  char entrada[31];
  char * separado;
  gets(entrada);
  separado = strtok (entrada," ");
  while (separado != NULL)
  {
    printf ("%s\n",separado);
    separado = strtok (NULL, " ");
  }
  return 0;
}

I found this code in a forum gringo, someone knows if it has a simpler way or explain to me how it works? I did not understand     

asked by anonymous 04.10.2017 / 17:10

1 answer

2

Here is an example that can convert a string containing data separated by space and store it in a vector:

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


char ** strsplit( const char * src, const char * delim )
{
    char * pbuf = NULL;
    char * ptok = NULL;
    int count = 0;
    int srclen = 0;
    char ** pparr = NULL;

    srclen = strlen( src );

    pbuf = (char*) malloc( srclen + 1 );

    if( !pbuf )
        return NULL;

    strcpy( pbuf, src );

    ptok = strtok( pbuf, delim );

    while( ptok )
    {
        pparr = (char**) realloc( pparr, (count+1) * sizeof(char*) );
        *(pparr + count) = strdup(ptok);

        count++;
        ptok = strtok( NULL, delim );
    }

    pparr = (char**) realloc( pparr, (count+1) * sizeof(char*) );
    *(pparr + count) = NULL;

    free(pbuf);

    return pparr;
}


void strsplitfree( char ** strlist )
{
    int i = 0;

    while( strlist[i])
        free( strlist[i++] );

    free( strlist );
}


int main( int argc, char * argv[] )
{
    int i = 0;
    char ** vec = NULL;

    vec = strsplit( "3 pratos de trigo para 3 tigres tristes", " " );

    while( vec[i] )
    {
        printf("[%d] %s\n", i , vec[i] );
        i++;
    }

    strsplitfree( vec );

    return 0;
}

Output:

$ ./teste 
[0] 3
[1] pratos
[2] de
[3] trigo
[4] para
[5] 3
[6] tigres
[7] tristes
    
04.10.2017 / 17:53