Question

For example, I have:

char *string = "S 27 64 Stack";
char *string2 = "R 9 3 Overflow";

How can i separate them into different strings? I want them to be like:

char *temp,*temp2,*temp3;
temp = S, temp2 = 27, temp3 = 64. Or:
temp = R, temp2 = 9, temp3 = 3.

I don't know if user types one-digit numbers or one-digit numbers. I wrote:

char *input; input = malloc(100*sizeof(char));
char *temp, *temp2,*temp3;

   else if(input[0] != NULL){


      if( *(input+2) != ' ' && *(input+4) != '0'){

       temp = strtok(input, " ");
       temp2 = strtok(input+2," ");
       temp3 = strtok(input+4," ");

      }

      else if( *(input+3) != ' '){

       temp = strtok(input, " ");
       temp2 = strtok(input+2, " ");
       temp3 = strtok(input+5, " ");
      }

   }

There is no problem when I try to use whether one-digit algorithm or two-digit algorithm alone. But, when i try to link them and use together, I just see Segmentation Fault(Core dumped) error.

Any help is appreciated.

Was it helpful?

Solution

The second and third calls to strtok should have a NULL as first parameter, try to replace

temp = strtok(input, " ");
temp2 = strtok(input+2," ");
temp3 = strtok(input+4," ");

by

temp = strtok(input, " ");
temp2 = strtok(NULL, " ");
temp3 = strtok(NULL, " ");

Then you don't need the if input[0], if input[2], ...

See the doc for strtok: http://www.cplusplus.com/reference/cstring/strtok/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top