1

How do I extract the hours, minutes, seconds, and AM/PM string from input similar to this using stringstream?

Input:

07:05:45PM
David
  • 1,034
  • 11
  • 20
  • 1
    Using boost http://stackoverflow.com/questions/3786201/how-to-parse-date-time-from-string can be useful – 550 Jul 15 '15 at 06:27

1 Answers1

3

Something along the lines of this:

unsigned int hour;
unsigned int minute;
unsigned int second;
char colon1;
char colon2;
string AMPM;

if (stream >> hour >> colon1 >>minute >> colon2 >> second >> AMPM)
{
    if (colon1 == ':' && colon2 == ':')
    {
        if ((hour < 12) && (minute < 60) && (second < 60))
        {
            if (AMPM == "AM")
            {
                // do nothing
            }
            else if (AMPM == "PM")
            {
               hour += 12;

            }
            else
            {
                //freak out
            }
        }
        else
        {
            //freak out
        }
    }
    else
    {
        //freak out
    }
}
else
{
    //freak out
}
user4581301
  • 33,082
  • 7
  • 33
  • 54