Search code examples
c++c++11tokenize

tokenize string with delimiter "/"


Hello guys I am facing a problem because I can't come up with a method that will take a string(it is actually a date in this form day/month/year) as parameter and tokenize it in a vector or an array. Could someone help out? I know that there are many topics about this but I couldn't find any solutions that don't include boost (that I dont want to use).


Solution

  • If you want to parse a date, the obvious starting point would be std::get_time:

    struct tm t;
    
    std::cin >> std::get_time(&t, "%d/%m/%Y");
    

    This puts the result into a struct tm rather than a vector. This way you can access the day of the month (for example) as t.tm_mday instead of trying to remember that x[1] is the day, and x[2] is the year (or whatever).

    You also get a fair number of other routines that know how to manipulate a date/time in this format, along with mktime, which can convert it to a time_t (for which quite a few more useful routines are provided).