-6
getline(cin,s);
istringstream iss(s);
do
{
    string sub;
    iss>>sub;
    q.insert(sub);
 }while(iss);

I used this technique when question wanted me to split on the basis of space so can anyone explain me how to split when there's a particular delimiter like ';' or ':'.

Someone told me about strtok function but i am not able to get it's usage so it would be nice if someone could help.

James Mills
  • 17,799
  • 3
  • 45
  • 59
vs13
  • 3
  • 2
  • 4

1 Answers1

17

First, don't use strtok. Ever.

There's not really a function for this in the standard library. I use something like:

std::vector<std::string>
split( std::string const& original, char separator )
{
    std::vector<std::string> results;
    std::string::const_iterator start = original.begin();
    std::string::const_iterator end = original.end();
    std::string::const_iterator next = std::find( start, end, separator );
    while ( next != end ) {
        results.push_back( std::string( start, next ) );
        start = next + 1;
        next = std::find( start, end, separator );
    }
    results.push_back( std::string( start, next ) );
    return results;
}

I believe Boost has a number of such functions. (I implemented most of mine long before there was Boost.)

James Kanze
  • 146,674
  • 16
  • 175
  • 326