split date char array by delimiter

i have a list of date format 1-12-2011 that i get from a txt file.

char date[30];
fstream fin("date.txt");

fin >> date;

how do i split the date array to 3 array of char day[],char month[] and char year[] for my structure list? using delimiter '-' so i get 1 to day, 12 to month and 2011 to year.

struct date{
string day;
string month;
string year;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <string>
#include <sstream>
#include <iostream>

int main()
{
    const std::string date = "1-12-2011" ;
    constexpr char DELIMITER = '-' ;

    // split date into three strings
    {
        std::istringstream stm(date) ;
        std::string day, month, year ;
        std::getline( stm, day, DELIMITER ) ;
        std::getline( stm, month, DELIMITER ) ;
        std::getline( stm, year ) ;
        std::cout << "string: " << day << ' ' << month << ' ' << year << '\n' ;
    }

    // split date into three integers
    {
        std::istringstream stm(date) ;
        int day, month, year ;
        char delim ;
        stm >> day >> delim ;
        stm >> month >> delim ;
        stm >> year ;
        std::cout << "int: " << day << ' ' << month << ' ' << year << '\n' ;
    }
}
Using strtok() should resolve your problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <string.h>
#include <string>

using namespace std;

struct Date
{
   Date()
   {
   }

   Date(char* _day, char* _month, char* _year)
      : day(_day)
      , month(_month)
      , year(_year)
   {
   }
   string day;
   string month;
   string year;
};

int main()
{
   Date dates[30];
   char date[] = {"1-12-2011"};
   char buffer[3][5];
   char* pch = strtok(date, "-");
   int n(0);
   while (pch)
   {
      strcpy(buffer[n++], pch);
      pch = strtok(NULL, "-");
   }
   dates[0] = Date(buffer[0], buffer[1], buffer[2]);
}
Last edited on
Topic archived. No new replies allowed.