如何在C ++中使用stringstream从字符串中提取时间

时间:2015-07-15 06:20:02

标签: c++ time

如何使用stringstream从输入中提取小时,分钟,秒和AM / PM字符串?

输入:

07:05:45PM

1 个答案:

答案 0 :(得分:3)

有些事情如下:

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
}