C++ how to take user input of time and seperate it into hours and minutes?

I need to take a users input such as 10:35 and put it into a variable of hours and minutes. How can I do this using the colon as the separate for the two? This is how the assignment requires it be entered.

Example of what I am doing.

int main()
{
char again = 'y';
int userHours = 0;
int userMinutes = 0;

while (again == 'y')
{
cout << "Enter a time in 24-hour notation: ";
cin >> userHours >> ":" >> userMinutes;
}
return 0;
}

2014-03-04T04:19:51Z

Actually I already solved it thanks to the people on stackoverflow. Just need a variable for the colon, so I just added the lines.

char colon;

cin >> userHours >> colon >> userMinutes;

cja2014-03-03T09:28:24Z

Favorite Answer

You should do something like this:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

const char delim = ':';
const unsigned hoursPerDay = 24;
const unsigned minutesPerHour = 60;

int main(int argc, char *argv[]) {
    string in;
    stringstream ss;
    unsigned hours, minutes;
    char c;

    while (true) {
        cout << "Enter time (HH" << delim << "MM) : ";
        getline(cin,in);
        ss.clear(); ss.str(in);
        if ((ss >> hours >> c >> minutes) &&
                (c == delim) &&
                (hours < hoursPerDay) &&
                (minutes < minutesPerHour)) {
            cout << setw(2) << setfill('0') << hours << delim
                      << setw(2) << setfill('0') << minutes << endl;
        }
    }
    return 0;
}

#if 0

Sample run:

Enter time (HH:MM) : 13:45
13:45
Enter time (HH:MM) : 12
Enter time (HH:MM) : 9:09
09:09

#endif