Noobart
Noobart

Reputation: 3

Storing a string token into an array

I am using C++ to tokenize a string using a delimiter and I can output the current token using cout in a while loop. What I would like to do is store the current value of the token in an array so that I may access it later. Here is the code I have now:

string s = "Test>=Test>=Test";
string delimiter = ">=";
vector<string> Log;
int Count = 0;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
strcpy(Log[Count].c_str(), token.c_str());
Count++;

s.erase(0, pos + delimiter.length());
}

Upvotes: 0

Views: 1420

Answers (2)

BlackMamba
BlackMamba

Reputation: 10252

push_back() will do what you need.

Upvotes: 0

JoshG79
JoshG79

Reputation: 1687

Just use push_back on the vector. It will do a copy for the token into the vector for you. No need to keep count; no need for strcpy:

string s = "Test>=Test>=Test";
string delimiter = ">=";
vector<string> Log;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
    token = s.substr(0, pos);
    Log.push_back(token);
    s.erase(0, pos + delimiter.length());
}

Upvotes: 1

Related Questions