Mega Code Archive

 
Categories / C++ Tutorial / String
 

Use strtok() to extract keys and values stored in keyvalue pairs within a string

#include <iostream> #include <cstring> using namespace std; int main() {   char kvpairs[] = "count=10, name=\"Joe, jr.\", max=100, min=0.01";   char kvdelims[] = " =,";   char *tok;   tok = strtok(kvpairs, kvdelims);      while(tok) {     cout << "Key: " << tok << " ";     if(!strcmp("name", tok)) {       tok = strtok(NULL, "\"");     }     else {       tok = strtok(NULL, kvdelims);     }     cout << "Value: " << tok << endl;     tok = strtok(NULL, kvdelims);    }   return 0; }