Originally Posted by
tneva82
I use what I'm most comfortable with. Never been comfortable with string class, even less with their ioclasses, haven't seen anything that does the job of strtok(which my program depends heavily. No strtok equilavent, no go. Is there equilavent of fscanf either? Another function that is absolutly _essential_ and used more than I dare to count. If there's not equilavent in c++ then it's just ugly situation when I have to redesign design from the scratch).
I use tools that help me. C++ has tools I find useful so I use them. But if they don't have tools I need(like strtok. Point me to c++ function that does same job? I have tried to look but haven't found so far one) I use them. Simple as that. I use whatever allows me to get the job done most easily.
With Boost, a tokenizer class exists that allow one to reap the tokens from a string.
If you don't want to use boost, then here's strtok()... my version:
Code:
std::vector<std::string> strtok(const std::string& str, const std::string& delim)
{
std::vector<std::string> tokens;
size_t pos = 0;
size_t loc = str.find_first_of(delim, pos);
if (loc == std::string::npos)
{
tokens.push_back(str);
}
else
{
while (loc != std::string::npos)
{
tokens.push_back(str.substr(pos, loc - pos));
pos = loc + 1;
loc = str.find_first_of(delim, pos);
}
}
return tokens;
}
Example usage:
Code:
void displayString(const std::string& str)
{
std::cout << str << std::endl;
}
int main()
{
const std::string line = "abc*def*ghi*jkl*";
std::vector<std::string> tokens = strtok(line, "*");
std::for_each(tokens.begin(), tokens.end(), displayString);
}
Bookmarks