Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use strtok to parse string at whitespace?

Tags:

c

string

I am trying to use strtok() to parse a string deliminated by spaces. From what I can tell, I am using it correctly, but it won't run on ideone.com. Is there anything wrong with the following code? I just get Runtime error time: 0 memory: 2288 signal:11

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

static void test(char *command)
{
    char* output = strtok(command, " ");
    printf("%s\n", output);
}

int main(void) {

    test("set_rate 200");

    return 0;
}

Here it is on ideone.com if you want to try it.

like image 339
boltup_im_coding Avatar asked Dec 15 '22 05:12

boltup_im_coding


2 Answers

Always consult the man pages first.

strtok(3) says:

Be cautious when using these functions. If you do use them, note that:

  • These functions modify their first argument.

  • These functions cannot be used on constant strings.

like image 123
Jonathon Reinhart Avatar answered Jan 13 '23 15:01

Jonathon Reinhart


strtok will modify the string passed as the first parameter, so you can't pass a string literal, change your main like this:

int main(void) {  
    char str[] = "set_rate 200";
    test(str);
    return 0;
}

str here is an char array, but not a string literal.

like image 23
Yu Hao Avatar answered Jan 13 '23 14:01

Yu Hao