Extracting substrings from a char variable

I have a char variable with the following:

2012-12-01_12:00:00

I am trying to extract the year, month, day and hour and convert each to integers. I am not used to C++. Then, store each in an integer variable:

int year, month, day, hour, minute, second;



Thank you,

Scott
one way, maybe not the best is to use string.erase()
once you have the right values, change to int.

*edit* you don't need all those headers :) They are just what I start with a new program.

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <conio.h>
#include <cstdlib>
#include <dos.h>
#include <fstream>
#include <iostream>
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <time.h>
#include <windows.h>


using namespace std;

int main()
{
//                 1234567890123567890
string datestring="2012-12-01_12:00:00";
string year, month, day, hour, minute, second;
// int iyear, imonth, iday, ihour, iminute, isecond;
year = datestring;
year.erase(4,20);
month = datestring;
month.erase(0,5);
month.erase(2,20);
day = datestring;
day.erase(0,8);
day.erase(2,20);
hour = datestring;
hour.erase(0,11);
hour.erase(2,20);
minute = datestring;
minute.erase(0,14);
minute.erase(2,20);
second = datestring;
second.erase(0,17);
cout << " Your original string is : ";
cout <<datestring<<endl;
cout << " Your string values are:   ";
cout << year << " ";
cout << month << " ";
cout << day << " ";
cout << hour << " ";
cout << minute << " ";
cout << second << endl;

// These are your int's.
int iyear = atoi(year.c_str());
int imonth = atoi(month.c_str());
int iday = atoi(day.c_str());
int ihour = atoi(hour.c_str());
int iminute = atoi(minute.c_str());
int isecond = atoi(second.c_str());

cout << " Your INT values are:      ";
cout << iyear << " ";
cout << imonth << " ";
cout << iday << " ";
cout << ihour << " ";
cout << iminute << " ";
cout << isecond << endl;


return 0;
}
Last edited on
Topic archived. No new replies allowed.