I compiled your program and I see what you mean. The problem is that scanf doesn't handle invalid inputs very well, such as trying to read in a string into an integer variable. When you try to do that, scanf gets confused, and simply continues the execution of the program, but it
does not flush the input buffer first. So if the scanf is in a loop, the next time it it executed the original string you had entered will still be in the input buffer, and scanf will fail again.
I can see two solutions to this problem:
1) Manually flush the input buffer whenever an invalid input is provided.
2) Utilize the cin instruction instead of scanf. This is in general a better practice since printf / scanf are old instructions with a lot of issues.
However, if you still want to use scanf, there's a way to solve the problem. As I said, we gotta make sure the input buffer is flushed when scanf fails. The code is below. This is what it does:
1) Define the variable
check to know whether scanf fails.
2) When we read an input with scanf, we use the syntax "check = scanf(...)". With this, the result of the "read" operation is saved in the variable
check. The result itself is the number of read variables (one in your case), or an "EOF" if scanf fails.
3) After the scanf, we just test the "check" variable: if it has any value other than 1 (remember 1 also means "logical true"), then the input was incorrect and we have to make the user enter it again ...
4) ... but before we can do that, we must make sure the input buffer is cleared. We do this by invoking scanf with the string "%*[^\n]", which reads anything in the input buffer until the end of line. The important thing here is that the input is
ignored; scanf never tries to assign it to a variable, so we avoid any problem with the input.
Code:
#include <stdio.h>
int main (){
// here u enter the 3 integers of time
int hrs, min, sec;
int check, exit;
printf("please enter the hrs now\n");
check = scanf("%d",&hrs);
// if the time was wrong this will make u inter the number again
while (!check) {
scanf("%*[^\n]");
printf("this time is invalid please enter a valid number\n");
check = scanf("%d",&hrs);
}
printf("please enter min now\n");
check = scanf("%d",&min);
while (!check) {
scanf("%*[^\n]");
printf("this time is invalid please enter a valid number\n");
check = scanf("%d",&min);
}
printf("please enter sec now\n");
check = scanf("%d",&sec);
while (!check) {
scanf("%*[^\n]");
printf("this time is invalid please enter a valid number\n");
check = scanf("%d",&sec);
}
// if evrything is going ok , then the output will be as the following
printf("the time is %02d:%02d:%02d\nPress any key to exit...",hrs,min,sec);
scanf("%i",&exit);
return 0;
}