'If true statement quits the program in C [closed]
I'm trying this simple code. But It quits the program by doing nothing when the statement is true. Why the program is behaving like this?
#include <stdio.h>
int main() {
int hour,minute,second;
printf( "Enter time (in HH:MM:SS) " );
scanf( "%02d:%02d:%02d", &hour, &minute, &second );
if ( scanf( "%02d:%02d:%02d", &hour, &minute, &second ) == 1 ) {
printf( "Entered time is %02d:%02d:%02d\n", hour, minute, second );
printf( "Regular time is %02d:%02d:%02d\n", hour-12, minute, second );
}
else {
printf( "Input is inapplicable" );
}
return 0;
}
Solution 1:[1]
I'm sure you meant
printf("Enter time (in HH:MM:SS) ");
if(scanf("%02d:%02d:%02d",&hour,&minute,&second) == 3){
The code you have cleary waits for more input after providing the time.
Solution 2:[2]
Thanks All.This is working.
#include <stdio.h>
int main() {
int hour,minute,second;
printf("Enter time (in HH:MM:SS) ");
if(scanf("%02d:%02d:%02d",&hour,&minute,&second) == 3){
printf("Entered time is %02d:%02d:%02d\n",hour, minute, second);
printf("Regular time is %02d:%02d:%02d\n",hour-12, minute, second);
}
else{
printf("Input is inapplicable");
}
return 0;
}
Solution 3:[3]
I predict the problem is that you set an if statement that would check if the values of minutes, hours and seconds equal 1 and it shouldn't be equaled to one, it should equal a different value.
if(scanf("%02d:%02d:%02d",&hour,&minute,&second) == 1)- This is a wrong part
it should be if(scanf("%02d:%02d:%02d",&hour,&minute,&second) >= 1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Omar Kotb |
