Your problem, of course, is that you are using sscanf . And that you use a special type for hours and minutes, instead of of int . Since you are parsing a string of exactly 5 characters, the simplest solution is simply to make sure that all characters are legal in this position using isdigit for characters 0, 1, 3 and 4 and compared to ':' for character 2. Once you have this done, it is trivial to create std::istringstream from a string and input to int , a char (which you will ignore later) and a second int . If you want to be more flexible in input, for example, allowing things like "9:45" , for example, you can skip the initial checks and just type in int , char and int , then check that char contains ':' (and that there are two int are in range).
As for your sscanf tag: you are asking it to match something like "12[:]34" , which is not what you give it. I'm not sure if you are trying to use "%hhd:%hhd" , or if for some reason you really need a character class, in which case you should use [ as a conversion specifier, and then ignore the input: "%hhd%*[:]%hhd" . (This would allow taking more than one character as a separator, but for the rest I see no advantage. In addition, technically, at least using %d and then passing the address of unsigned integral types is not supported, %hhd should be signed char . In practice, however, I do not think that you will ever have problems for non-negative input values ββless than 128.)
source share