I strongly recomend using std::string's functions (find() and substr()) but
Let's say you have to use c-style functions and c-style strings. then...
Here are the problems in our code :
1. You don't include <cstring>, this header defines strtok and strcpy.
2. You make a varibale 'i' on line 14, altough you never use it.
3. You don't need a for loop here, you don't need to know how many tokens will be there.
You have to test whether strtok() returns 0.
4. Before the loop you use strtok (line 22), and before you get the results out of p, in the first iteration you overwrite it again (line 33).
Here is a corrected code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
int main() {
char *cstr, *p;
vector<string> obstypes;
string str("L1 L2 C1 P2 P1 S1 S2");
cstr = new char[str.size() + 1];
strcpy(cstr, str.c_str());
p = strtok(cstr, " ");
while (p) { // while (p != 0)
obstypes.push_back(p);
p = strtok(NULL, " "); //We use strtok again AFTER we took out the result.
}
for(unsigned i = 0; i < obstypes.size(); ++i) {
cout << obstypes[i] << endl;
}
delete[] cstr;
return 0;
}
| |
EDIT : Always check out the reference for a function
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
There is an example very similar to yours.