Split date string into separate variables c++

... by Bittle in Programming Help August 26, 2018


We have the following string input "mm/dd/yyyy" (a date) and we want to split it into its own variables for month, date and year.


One way to do this is to split at every / and keep splitting until the end, and then parse the current split with atoi (string to int conversion). We must keep track of what variable we are currently setting to avoid errors. The following snippet works great.

#include <iostream>

int main() {
    // date in mm/dd/yyyy format
    char date[] ="08/21/1998";
    // pointer to current split section
    char * pch;
    // info needed
    int month = -1, day = -1, year = -1;

    // split the date from beginning to the first occurrence of /
    pch = strtok(date,"/");
    // while we have more / chars
    while (pch != NULL)
        // set the variables
        int num = atoi(pch);
        if(month == -1) month = num;
        else if(day == -1) day = num;
        else if(year == -1) year = num;

        // continue splitting the string
        pch = strtok (NULL, "/");

    // check if we got correct data
    printf("%d %d %d", month, day, year);
    return 0;

Comments (0)

Search Here