Click here to Skip to main content
15,886,091 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to check if the input is in the time format HH:MM. Valid time is from 00:00 to 23:59. I did:
C#
printf("Please enter you age: ");
scanf("%f", &age);
if (age < 18) 
{
    printf("Too young, we can't serve you.\n");
    return 1;
}


C++
printf("Please enter the time in the format HH:MM: ");
scanf("%c%c%c%c%c", &h1, &h2, &colon, &m1, &m2);
if ((h1 < '0' || h1 > '2') || (h2 < '0' || h2 > '9') || (m1 < '0' || m1 > '5') || (m2 < '0' || m2 > '9')) 
{
    if (h1 == '2' && h2 > '3')
    {
            printf("The time is not in the format HH:MM.");
            return 1;
    }
}

but it doesn't work.
Posted
Updated 12-Apr-15 11:38am
v7

1 solution

C++
if (h1 == '2' && h2 greater than '3')

If any character is invalid, this test is redundant at this point. It should be part of the initial if statement. Something like:
C++
if ((h1 < '0' || h1 > '2') || (h2 < '0' || h2 > '9') || (m1 < '0' || m1 > '5') || (m2 < '0' || m2 > '9') || (h1 == '2' && h2 > '3'))
{
        printf("The time is not in the format HH:MM.");
        return 1;
}
 
Share this answer
 
Comments
Maciej Los 12-Apr-15 13:48pm    
5ed!
yngwie123 12-Apr-15 14:38pm    
It's confusing. Why do I get "The time is not in the format HH:MM." when I hit "10:00", for example? I tried various inputs but they all don't seem to work.
Frankie-C 12-Apr-15 15:07pm    
In your original code you messed up the conditions for 'correct' value and 'wrong' one.
in the line:
if ((h1 < '0' || h1 > '2') || (h2 < '0' || h2 > '9') || (m1 < '0' || m1 > '5') || (m2 < '0' || m2 > '9'))
you checked all wrong conditions, you must have returned immediatly as 'wrong' format. But you added another check:
if (h1 == '2' && h2 greater than '3')
So all wrong inputs, but not having hour bigger that 23 become correct ;-)
Maybe in your checks reverting the conditions you got an error again making wrong all 'correct' values less than 23.
The correct coding of your test should have been:
if ((h1 < '0' || h1 > '2') || (h2 < '0' || h2 > '9') || (m1 < '0' || m1 > '5') || (m2 < '0' || m2 > '9'))
{
printf("The time is not in the format HH:MM.");
return 1;
}
else if (h1 == '2' && h2 > '3')
{
printf("The time is not in the format HH:MM.");
return 1;
}
yngwie123 12-Apr-15 15:40pm    
It still doesn't work. Maybe it's logically wrong?
Frankie-C 12-Apr-15 16:31pm    
What don't work? It works pretty good.
On what values it fails for you?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900