It doesn't compile because c_str()
returns a const char*
, it's supposed to be a constant pointer to not modifiable internal string
buffer. On the other hand strtok()
accepts a char*
because it modifies its input string.
Now you have two options: get a C string usable from strtok()
or rewrite everything to be C++.
Create a new modifiable C string from your C++ string:
char* modifiableLine = strdup(line.c_str());
x = atoi((strtok(modifiableLine, "(,)"));
// Other processing
free(modifiableLine);
You can do it if you have to keep a big amount of C code wrapped inside a C++ function/class. A better solution is to use what C++ Standard Library offers (also dropping atoi()
C function if C++ 11). Let's first write an helper function:
int readNextInt(istringstream& is, const string& delimiters) {
string token;
if (getline(is, token, delimiters))
return stoi(token);
return 0; // End of stream?
}
Used like this:
istringstream is(line)
x = readNextInt(is, "(),");
xx = readNextInt(is, "(),");
xxx = readNextInt(is, "(),");
Please note that standard C++ function getline()
doesn't accept a string
for delimiters parameter but a single char
only then you have to write your own overloaded version. Take a look to this post for good and nice possible implementation (you may also simply replace getline()
with is >> token
after is.imbue()
, see given example).
Well...if you're already using Boost then you may simply use boost::tokenizer
.