I am making a program where I need to use a function which stores a tokens of a string in a vector. The function did not work properly so I tried the function on a smaller program. Of course, I used string tokenizer function. But it is not working as expected. First, here's the code:
#include <vector> #include <string> #include <cstring> using namespace std; int main() { vector<string> v; string input = "My name is Aman Kumar"; char* ptr = strtok((char*)input.c_str(), " "); v.push_back((string)ptr); while(ptr) { ptr = strtok(NULL," "); v.push_back((string)ptr); } cout<<"Coming out"; for(string s:v) { cout<<s<<endl; } }
Now the problems. I think the issue has something to do with the command:
(string)ptr
This thing works perfectly in the first call, but gives error when present in the while loop. If I comment it out and print ptr, then it works okay, but then the program terminates after the while loop, and doesn't even execute
cout<<"coming out";
leave alone the contents of the vector. But again, if I don't print ptr too, then the first Token "My" which was stored in the vector gets printed. I literally cannot find what is causing this. Any suggestion would be helpful.
char* ptr = strtok((char*)input.c_str(), " ");
this could be a problem.c_str()
returns const C string and you must not change it. But you are removing the constness with(char*)input.c_str()
and passing it tostrtok
.strtok
modifies the strings. That causes undefined behavior. – Briticisminput.c_str()
. Usestd::string
functions and<algorithm>
instead of the old C interface. – Nareshstd::istringstream stream(input); std::copy(std::istream_iterator<string>(stream), std::istream_iterator<string>(), std::back_inserter(v));
. – Naresh