-1

I am having trouble trying to converting time from 12 hour format to 24 hour format.

Note:- This is from an online test site and is filled with boilerplate code to work with the site, so I'm only going to post the part of the program where I am allowed to type.

string timeConversion(string s) {
    /*
     * Write your code here.
     */
     int hours = ((int) s[0])*10+((int) s[1]);
     char r[7];
     //cout<< sizeof(s)<<"\n";
     if(s[8]=='P')
     {
        hours=hours+12;
        r[0]=(char) (hours/10);
        r[1]=(char) (hours%10);
        for (int i=2;i<8;i++)
           {
            r[i]=s[i];
           }
     }else
        {
            for(int i=0;i<8;i++)
            {
                r[i]=s[i];
            }
        
        }  
     return r;
}

Here is the input and outputs of test

Input(stdin):-
07:05:45PM

My output(stdout):-
6:05:45

Expected output:-
19:05:45

Now I test line 5 (i.e the line where i convert the hours section into an integer) in another compiler by itself and for some reason instead of properly converting its showing hours=534

Can you guys tell me what went wrong and how to fix it?

  • 3
    _Don't go beyond this fence, you're leaving the defined behavior zone!_ (B. Stroustrup) – πάντα ῥεῖ Sep 21 '20 at 16:05
  • `s[0]` contains the codepoint of the zeroth element in the string, as a `char`; while `char`s can be treated as numbers (codepoints are just numbers after all), the number of the codepoint is not equal to the number its corresponding glyph represents: `'0' != 0`, `'1' != 1`, etc. – Cameron Sep 21 '20 at 16:06
  • `ch - ‘0’` Will give you the numeric value represented by a digit character (`’0’..’9’`). – Pete Becker Sep 21 '20 at 17:58

1 Answers1

0

I found out what was going wrong with my code earlier. The reason why it didnt work is because c++ doesn't convert the numerical character into the actual numerical value, rather it converts it into the corresponding ascii value for which starts at 48 for "0" and ends at 57 for "9" Statement to use for converting hours in the string and vice versa would be to

string -> int

int hours = (((int) s[0])%48)*10+(((int) s[1])%48);

or

int hours = (((int) s[0])-48)*10+(((int) s[1])-48);

int -> string

r[0]=(char) ((hours/10)+48);
r[1]=(char) ((hours%10)+48);