Reputation: 4218
I am receiving string such as "2011-08-12,02:06:30"
from the server which specifies data and time.
But how to convert it into int and store like
int year = 2011, month =08, day = 14, h = 02, min = 06, sec=30
.
Upvotes: 1
Views: 233
Reputation: 14535
You can use stringstream
class in C++.
#include <iostream>
// for use of class stringstream
#include <sstream>
using namespace std;
int main()
{
string str = "2011-08-12,02:06:30";
stringstream ss(str);
int year, month, day, h, min, sec;
ss >> year;
ss.ignore(str.length(), '-');
ss >> month;
ss.ignore(str.length(), '-');
ss >> day;
ss.ignore(str.length(), ',');
ss >> h;
ss.ignore(str.length(), ':');
ss >> min;
ss.ignore(str.length(), ':');
ss >> sec;
// prints 2011 8 12 2 6 30
cout << year << " " << month << " " << day << " " << h << " " << min << " " << sec << " ";
}
Upvotes: 4
Reputation: 32538
You can also use the strptime()
function on any POSIX-compliant platform, and save the data into a struct tm
structure. Once in the format of a struct tm
, you will also have some additional liberties to take advantage of other POSIX functions the time format as defined by struct tm
.
For instance, in order to parse the string being sent back from your server, you could do the following:
char* buffer = "2011-08-12,02:06:30";
struct tm time_format;
strptime(buffer, "%Y-%d-%m,%H:%M:%S", &time_format);
Upvotes: 1
Reputation: 4954
You could either write your own string parser to parse the string into the necessary components (something like a Finite State Machine design would be good here), or...
Don't re-invent the wheel, and use something like the Boost Date & Time library.
Upvotes: 3
Reputation: 80633
The sscanf function will help you out much here.
int year, month, day, h, min, sec;
char * data = "2011-08-12,02:06:30";
sscanf(data, "%d-%d-%d,%d:%d:%d", &year, &month, &day, &h, &min, &sec);
Upvotes: 4