hh:mm:ss - time format

i have to create c++ program.
The program requires the time format hh : mm : ss and check the correctness of the input , eliminating the appropriate report , such as:
23:09:03 - correctly ,
2: 2: 2 - wrong format ,
12:02:94 - wrong time
05/14/35 - wrong format ,
qw2 : we34 - wrong format .

any help would be appreciated :)
First check is the number is not another character
then check if : is exist
then check is the number consist of 2 number
last check is the number is higher that highest value or the opposite
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream> 
#include <string> 
#include <sstream> 

using namespace std; 

bool isValidTime(int, int, int); 
const char delim = ':'; 

int main(int argc, char *argv[]) { 
    string in; 
    stringstream ss; 
    char c1, c2; 
    int hr, min, sec; 

    cout << "Enter HH:MM:SS : " << endl; 
    while (true) { 
        cout << "> "; 
        getline(cin,in); 
        ss.clear(); ss.str(in); 
        if ((ss >> hr >> c1 >> min >> c2 >> sec) && 
                (c1 == delim) && (c1 == c2) && 
                isValidTime(hr, min, sec)) { 
            cout << "Good Format" << endl; 
        } else { 
            cout << "Bad time format" << endl; 
        } 
    } 
    return 0; 
} 

bool isValidTime(int hr, int min, int sec) { 
    return (((hr >= 0) && (hr < 24)) && 
                    ((min >= 0) && (min < 60)) && 
                    ((sec >= 0) && (sec< 60))); 
} 
  



this is what i'm working with so far but i have problem that it doesnt recognise 2 symbols
for example i ente 2:2:2 it says its okay

how do i do that? :)
Idk if this a proper way but you can use string instead of int, and to compare it with other number you can use stoi()
i don't think i follow what you try to say... can you be more specific? :)
I get a better idea, check if the input string size is 8. 6 numeric and 2 :
that could work maybe just 8 :)
Have you used arrays?

Given 23:09:03 is good, you can see that:
- you need to check the type of elem 0-7 are the type expected (inc. that there are just 8 elems.)
- then check each digit pair is in range.

Or exploit the fact that the ':' turns up every 3 chars?

Andy

PS Here I would be tempted to code my own conversion function that use stoi or whatever (as it's always 2 chars to a value)
Last edited on
thanks everyone for help and ideas i just added one more function that checks if there is 8 elements and since i had everything else already defined i didn't go any deeper than that :)

thanks again :) works like a charm :)
Topic archived. No new replies allowed.