i need to convert time in 12 hr to the 24 hr format.
ive hardcoded the 12 hour time for now to make stuff simpler.
my logic: input sting 07:05:45PM extract last 2 chars. if AM check is first 2 chars are 12.. if yes chance them to 00 else output as it is if PM check if first 2 digits are 12 ..if yes leave as it is if not then add 12 to first 2 digits
#include<stdio.h> #include<stdlib.h> #include<string.h> char* timeConversion(char* s1) { // input sting 07:05:45PM // extract last 2 chars. // if AM // check is first 2 chars are 12.. if yes chance them to 00 // else output as it is // if PM // check if first 2 digits are 12 ..if yes leave as it is // if not then add 12 to first 2 digits char s[strlen(s1) + 1]; strcpy(s, s1); char suffix[3]; // pm am suffix[0] = s[strlen(s) - 2]; suffix[1] = s[strlen(s) - 1]; suffix[2] = '\0'; char xx[3]; // first 2 nos xx[0] = s[0]; xx[1] = s[1]; xx[2] = '\0'; s[strlen(s1) - 1] = '\0'; s[strlen(s1) - 2] = '\0'; if(strcmp(suffix, "AM") == 0) { if(strcmp(xx, "12") == 0) { s[0] = '0'; s[1] = '0'; strcpy(s1, s); } else { return s1; } } else { if(strcmp(xx, "12") == 0) { strcpy(s, s1); return s1; } else { int n; // 01 - 09 if(xx[0] == '0') { char x = xx[1]; n = x - '0'; // xx = itoa(n); } else { // 10, 11 n = atoi(xx); } n = n + 12; // itoa(n, xx, 10); sprintf(xx, "%d", n); s[0] = xx[0]; s[1] = xx[1]; } } strcpy(s1, s); return s1; } int main() { char *str = "07:05:45PM"; char *str1 = timeConversion(str); printf("%s\n", str1); return 0; } Bus error: 10 is what im getting on running the code
s1inside the function asstrpoints to a string literal which is a constant. You can try:char *str = "07:05:45PM";==>char str[] = "07:05:45PM";but I'm not sure it solves all problems.