vendredi 29 septembre 2017

Unable to convert 12-hour format to 24-hour format [duplicate]

This question already has an answer here:

I am solving a question which asks to convert 12-hour time format to 24-hour format. I am using C language to implement the program.

I don't know why, but the output of my program for any input in PM is something starting from 10. For example, for input 07:03:23PM the output should be 19:03:23, but my output comes out to be 10:03:23. For input 03:03:23PM, the output should be 15:03:23, but again my output comes to be 10:03:23.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

char* timeConversion(char* s)
{
    int t,k,i=1,l;
    char* r = malloc(50 * sizeof(char));
    if(s[8]=='P')
    {
        if(s[0]!='1'&&s[1]!='2')
        {
         t = ((s[1]-'0')*1+(s[0]-'0')*10) + 12;
         sprintf(r,"%d",t);
        }
        else
            r[0]='0';r[1]='0';
        for(i=2;i<8;i++)
        {
            r[i]=s[i];
        }

    }
    else
        for(i=0;i<8;i++)
            r[i]=s[i];
    r[i]='\0';
    return r;
}

int main() {
    char* s = (char *)malloc(512000 * sizeof(char));
    scanf("%s", s);
    int result_size;
    char* result = timeConversion(s);
    printf("%s\n", result);
    return 0;
}

In timeConversion function I have allocated a memory whose base address is pointed by char pointer r. In r I store the result after the conversion. I have used sprintf() to store the value of "integer" t (which contains the value of first two digits of time after conversion to 24-hour format) into "string" r.

I have checked the program using a debugger, and after the execution of sprintf() statement, r contains value 10 even though value stored in t is 19 for the first input case.

I don't know what is causing this problem.

Aucun commentaire:

Enregistrer un commentaire