1

I am trying to split my actual key on dot and then extract all the fields after splitting it on dot.

My key would look like something this -

t26.example.1136580077.colox

Below is the code I have which I was in the impression, it should work fine. But somehow whenever I am compiling this code, I always get -

 error: âstrtok_sâ was not declared in this scope

Below is my code

if(key) {
    vector<string> res;
    char* p;
    char* totken = strtok_s(key, ".", &p);
    while(totken != NULL)
    {
        res.push_back(totken);
        totken = strtok_s(NULL, ".", &p);
    }

    string field1 = res[0]; // this should be t26
    string field2 = res[1]; // this should be example
    uint64_t field3 = atoi(res[2].c_str()); // this should be 1136580077
    string field4 = res[3]; // this should be colox

    cout<<field1<<" "<<field2<<" "<<field3<<" "<<field4<<endl;
}         

I am running Ubuntu 12.04 and g++ version is -

g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

Any idea what wrong I am doing? And if there is any better way of doing it as well, then I am open to that suggestion as well. I am in the impression that using strtok_s will be more efficient and thread safe as well.

AKIWEB
  • 19,008
  • 67
  • 180
  • 294
  • 1
    `strtok_s` is for windows. You have a similar thread here: http://stackoverflow.com/questions/9021502/whats-the-difference-between-strtok-r-and-strtok-s-in-c – lolando Nov 26 '13 at 07:03
  • aah... I should have knows this before.. Then how to solve above problem using plain `strtok`? I believe, I cannot simply replace `strtok_s` with `strtok`? – AKIWEB Nov 26 '13 at 07:05
  • i think the solution of Joachim suits your need (i.e use the preprocessor directive to use `strtok_s` or `strtok_r` depending on your platform) – lolando Nov 26 '13 at 07:07
  • But there should be some other way as well to directly solve this problem using strtok function? And why to complicate things by using strtok_r and strtok_s. Initially I was in the impression that strtok_s will work anywhere but it looks like now I am mainly will be looking for solution in plain strtok or any other effcient way.. – AKIWEB Nov 26 '13 at 07:13

1 Answers1

4
#ifndef _MSC_VER
inline
char* strtok_s(char* s, const char* delim, char** context)
{
        return strtok_r(s, delim, context);
}
#endif
Radim Bača
  • 10,646
  • 1
  • 19
  • 33
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • Thanks Michael for the suggestion. How to use the above code in my C++ code? Should I put the above code at the very end of my c++ project? – AKIWEB Nov 26 '13 at 07:41