Strtok needs a literal delimiter?

Hi guys. Just checking to see if this is C++ according to Hoyle or just a quirk with Arduino flavor.

If I write this:

const char Delimiter=':';

 //Declare array and get first token.
    Token=strtok(receivedChars,Delimiter);   

I get broken data. I also tried these declarations for Delimiter:

char Delimiter;
String Delimiter;
char * Delimiter; //you never know. ;)

But strtok only works if I do it like so:

Token=strtok(receivedChars,":");

Which is fine, but I was just wondering if this is expected for strtok in general.
I'm using this for my reference.

Edit, sry: same thing applies to the second argument...

It's very clear. The first argument is

 char *str

pointer to char.

If you had included what you have in front of you for the declaration of

receivedChars

you would see, I think, that it is a point to char, or a character array, same same in C/C++.

So no getting creative. Use the argument types in the documentation.

a7

You can have multiple delimiters that’s why you pass a cString pointer so using double quotes even if you only have one.

const char * delimiters = ":";

Or you could use

const char delimiters[] = ":";

consider some generic code that tokenizes and convert numerics to values

char s [80];

#define MaxTok  10
char *toks [MaxTok];
int   vals [MaxTok];

// -----------------------------------------------------------------------------
int
tokenize (
    char       *s,
    const char *sep )
{
    unsigned n = 0;
    toks [n] = strtok (s, sep);
    vals [n] = atoi (toks [n]);

    for (n = 1; (toks [n] = strtok (NULL, sep)); n++)
        vals [n] = atoi (toks [n]);

    return n;
}

// -----------------------------------------------------------------------------
void dispToks (
    char * toks [])
{
    char s [40];
    for (unsigned n = 0; toks [n]; n++)  {
        sprintf (s, " %6d  %s", vals [n], toks [n]);
        Serial.println (s);
    }
}

// -----------------------------------------------------------------------------
void loop ()
{
    if (Serial.available ())  {
        int n = Serial. readBytesUntil ('\n', s, sizeof(s)-1);
        s [n] = 0;      // terminate string

        tokenize (s, ",");
        dispToks (toks);
    }
}

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (9600);
}

Because the second argument to strtok() is:
delim − This is the C string containing the delimiters.
You are passing a single character constant, not a C string which is a character pointer pointing to the first of zero or more characters ending in a null ('\0') character.

You can pass a constant C string several ways:

#define Delimiter ":"
or
const char *Delimiter = ":";
or
const char Delimiter[] = ":";

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.