1

I have a string,

"id,port,password,ssid,delay,flag,class,category"

Please tell me how can stringtok this and find out the "flag" value(0 or 1)?

Here is what I tried:

void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);
    ptr = strtok(input, ",");
    Serial.println(ptr);
    while (ptr != NULL) {
        ptr = strtok(NULL, ",");
        Serial.println(ptr);
    }
}

void loop(){}
  • I would remove the { and } in char input[] = {"id,port,password,ssid,delay,flag"}; – Juraj Jun 19 '19 at 8:21
  • 2
    Even with the (useless) braces Juraj suggest removing, your code works as expected. Please, be more specific about what your actual problem is. – Edgar Bonet Jun 19 '19 at 8:37
  • how 'flag' substring separately taken ? what modification that i want to made in program? – Jonson Jun 19 '19 at 8:57
  • based on position? 6th item? – Juraj Jun 19 '19 at 9:04
2

For strings with a fixed format like that (I assume it's a fixed format...) I normally just do a manual strtok of the whole thing into a set of pointers. No need for a loop. You can then just test the last one to see if the whole thing tokenised properly, since if anything before that fails then all other subsequent ones will fail and the last one will have failed.

void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);

    char *id = strtok(input, ",");
    char *port = strtok(NULL, ",");
    char *password = strtok(NULL, ",");
    char *ssid = strtok(NULL, ",");
    char *delay = strtok(NULL, ",");
    char *flag = strtok(NULL, ",");
    char *class = strtok(NULL, ",");
    char *category = strtok(NULL, ",");
    if (category != NULL) { // Everything up to and including category worked
        Serial.print("Flag: ");
        Serial.println(flag);
    }
}

void loop(){}

As an aside: if there is ever a chance any of the fields could be empty ("flag,,category" for example) then you should use strsep() instead of strtok() as I detail in my tutorial on splitting strings in C.

Not the answer you're looking for? Browse other questions tagged or ask your own question.