-1

I tried the following code from one of the guys who answer my previous question.

My case is I am trying to get the value 1.2597 in this string, and my non functional requirement is to use strtok instead of boost which is recommend by many fellow coders here.

However I got a issue casting result into a cstr* that can use the strtok.

I want to know how I can get 1.2597, and echo it out with strtok

string result= "CCY 1.2597 Down 0.0021(0.16%) 14:32 SGT [44]";

char *first = strtok(result, ' ');
char *second = strtok(0, ' ');
Community
  • 1
  • 1
Baoky chen
  • 183
  • 7
  • 15
  • 2
    `strtok()` takes a `char*`, not a `std::string` (don't pass `std::string::c_str()` as `strtok()` modifies the supplied string). Use `std::istringstream` instead. – hmjd Jul 24 '12 at 09:59
  • Just use `std::string.find()` as you did for finding the strin in your question. – steffen Jul 24 '12 at 10:07
  • my project got a requirement to use strtok to split the string. – Baoky chen Jul 24 '12 at 10:56
  • i tried many examples below but got error still. how do i use strtok to obtain 1.2597 with my string result="CCY 1.2597 Down 0.0021(0.16%) 14:32 SGT [44]"; – Baoky chen Jul 24 '12 at 10:56

3 Answers3

2

You can't use strtok directly on a C++ std::string. It requires a mutable zero-terminated C-style string, and there is no standard way to access the contents of a std::string in that form.

The simplest option (without using Boost or other non-standard libraries) is to use a C++ stream instead:

std::stringstream stream(result);
std::string first, second;
stream >> first >> second;

That could also convert the second token directly into a numeric type, if that's what you want.

If you really want to use strtok for some reason, then one possibility is to copy the string into a temporary mutable buffer:

std::vector<char> temp(result.begin(), result.end());
temp.push_back(0);

char * first = strtok(&temp[0], ' ');
char * second = strtok(0, ' ');

Be aware of the other major fault with strtok: it is not thread safe.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

This works:

std::string result= "CCY 1.2597 Down 0.0021(0.16%) 14:32 SGT [44]";
size_t pos0 = result.find(' ');+1
size_t pos1 = result.find(' ',pos0);
std::string final_result = result.substr(pos0,pos1-pos0);
steffen
  • 8,572
  • 11
  • 52
  • 90
1

Yeah, as Mike Seymore stated, you have to copy your std::string to a mutable buffer. Already including string.h, simply use strcpy to copy the std::string to a mutable char*. Dont forget to include space for null termination + actually inserting the '\0' ;D

std::string result = "...";
char* token;
char* buffer[res.length() + 1];  //Space for '\0'
strcpy(buffer, result.c_str());
buffer[res.length()] = '\0';     //insert '\0'
token = strtok(buffer, " ");
while (token != NULL) {
  /* work with token */
  token = strtok(NULL, " ");
}
Tomas Longo
  • 95
  • 1
  • 7