What's wrong in this program? (Convert 12 hour format to 24 hour time format) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What's wrong in this program? (Convert 12 hour format to 24 hour time format)

#include <stdio.h> #include <string.h> int main() { int hour, minute; char str; scanf("%d:%d %s", &hour, &minute, &str); if ((hour >= 0 && hour < 12) && (minute >= 0 && minute < 60)) { if (str == 'AM') { printf("%d:%d", hour, minute); } else { printf("%d:%d", hour + 12, minute); } } else if (hour == 12 && minute == 0) { if (str == 'AM') { printf("%d:%d", hour - 12, minute); } else { printf("%d:%d", hour, minute); } } return 0; }

29th Mar 2020, 11:14 AM
Sagar Thapaliya
Sagar Thapaliya - avatar
5 Answers
+ 4
you cannot compare strings like this in C, in your case I think It's better to compare the first character of str to 'A', like this : if (str[0]=='A') by the way, in C strings are between double quotes char str[]="my string"
29th Mar 2020, 1:16 PM
John Robotane
John Robotane - avatar
0
29th Mar 2020, 2:38 PM
Sagar Thapaliya
Sagar Thapaliya - avatar
0
John Robotane how can I display '00' instead of '0' ?
30th Mar 2020, 2:51 AM
Sagar Thapaliya
Sagar Thapaliya - avatar
0
Sagar Thapaliya try this : in the first if statement if((hour>=0 && ....{ if(str [0]=='A'){ printf("0%d:%d",hour,minute);} else ... and in the else if do the same else if(hour ==12.... { if (str[0]=='A') { printf("00:%d",minute); } else ...
30th Mar 2020, 7:30 AM
John Robotane
John Robotane - avatar
0
John Robotane I tried it previously but it does not work for all the cases😅
30th Mar 2020, 9:44 AM
Sagar Thapaliya
Sagar Thapaliya - avatar