1

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.

1
  • 1
    Sounds like you want to parse a string into a date/time object. Commented Aug 12, 2011 at 2:36

4 Answers 4

4

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 << " "; } 
Sign up to request clarification or add additional context in comments.

Comments

4

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); 

3 Comments

Straightforward and reliable :)
Ahhh. Not reliable as they don't type check their parameters. In your code it is easy to see but in larger programs if the seonds is defined a long way from the scanf() then a bug fix may result in changing the type of seconds from int to long. Yet the above code would still compile without error.
Not sure what you mean by 'defined a long way from the scanf', or 'bug fix'. But no, sccanf does not type check, that's a task for the programmer to validate his input string if required.
3

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.

Comments

1

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.