The problem is that c_str()
returns a const char*
, because the string
object is supposed to be the owner of the buffer where the encapsulated string is stored, so you are not entitled to modify it except through member functions of string
.
On the other hand, strtok()
accepts a pointer to (non-const
) char
, i.e. a char*
, and this is what the compiler complains about: you are trying to pass something non-modifiable to a function that wants to modify that thing.
If I may suggest a better approach which is more idiomatic in C++11, since you are using std::string
anyway, rather do the following:
#include <iostream>
#include <string>
int main()
{
std::string s = "Ana and Maria are dancing";
std::string::size_type start = 0;
std::string::size_type pos = s.find(" ");
while (pos != std::string::npos)
{
std::string tok = s.substr(start, pos - start);
std::cout << tok << " ";
start = pos + 1;
pos = s.find(" ", start);
}
}
The above code also removed this directive:
using namespace std;
It is commonly considered bad programming practice (especially when placed at global namespace scope), because it easily leads to name clashes with entities that belong to the std
namespace.