Set input stream delimiter

Hello, I want to be able to read data from cin in the following format:
07:00
where 07 is hours and 00 is minutes.

If instead of the : character there was a space I would just type:
cin >> hours >> minutes;

Is it possible to change the delimiter to : and treat it as a space?

I know how to achieve this using scanf like this:
scanf("%i:%i", &hours, &minutes);

My question is can I achieve this using cin?
Last edited on
The far as I know not. If there is a way, it should be in the reference-part of this site, but I couldn't find it (didn't search to well either, maybe you want to take a look yourself: http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E.html).

What you could do, using C++ style methods, is storing the whole thing in a string using getline (http://www.cplusplus.com/forum/articles/6046/), then use find() and substr() to seperate them into the different parts ("07" and "00") and after that you can use stringstream to 'translate' them into integers (see that article about getline(), 'how to get a number').
You can create a simple class and overload the >> operator

eg:
1
2
3
4
5
6
7
8
9
10
11
struct Time
{
	int hours, minutes;
};
istream &operator >> (istream &is, Time &t)
{
	is >> t.hours;
	is.ignore(1,':');
	is >> t.minutes;
	return is;
}
(This way requires valid input)
Thanks for the answers!
Bazzy, that works just as I want it to.

I also needed to output times in the same format so I overloaded the << operator too, like this:

1
2
3
4
5
6
7
ostream &operator << (ostream &os, Time &t)
{
    os << setfill('0') << setw(2) << t.hours;
    os << ":";
    os << setfill('0') << setw(2) << t.minutes;
    return os;
}


Thanks again for this good idea.
Topic archived. No new replies allowed.