Hi folks,

Can you help me try to figure this one out?

I am trying to create a program that will accept a string from a user input ( cin) in the HH:MM:SS format, and then convert this into seconds. However, I also want to avoid "fat-fingered"input by creating an error message that disallows special characters or alphabetical input ( other than the colons I need to separate the time stamp.)

I did manage to create a workaround, where I took an HH:MM:SS input, and then set this to an input string.

I then used assignment statements to set this string to be the same value as three new string values. I called a string.erase(x,y) to remove the unwanted characters so that the three string values then represent hours, minutes and seconds. I created a function from istringstream (#include <sstream>) to convert the string into an integer and then performed the math to convert the time string into seconds for further calculations.

Can anyone think of a better way to do this? If someone enters only a single character, or they enter a special character instead of a number then my program vaporizes. I tried creating an array, but every time I use the istringstream or the atoi function I get an error message from the compiler that I can't set a const char to a char.

Thanks in advance!


After getting the input string you could validate the string by first checking the string length to insure it is the correct length, then enter a loop and use isdigit() to check that each character is a digit or compare with ':' for a colon. If it passes all that then you could separate the input string into individual integers then validate again for valid ranges of hours, minutes and seconds. Finally convert all to seconds.