-4

To convert String to integer, I know there is a function atoi() but i found this one helps too! Please explain this int h1 = (int)str[1] - '0'; I founded this here http://www.geeksforgeeks.org/cpp-program-convert-time-12-hour-24-hour-format/

Juan Leni
  • 6,982
  • 5
  • 55
  • 87
  • How is this the same? And what is unclear? Everything will be explained by any beginner's C book. – too honest for this site Jul 07 '17 at 15:09
  • Nobody's going to go through that link. Where's `str` defined? Based on the actual code, this may not even compile (or even worse). – babon Jul 07 '17 at 15:09
  • https://stackoverflow.com/questions/628761/convert-a-character-digit-to-the-corresponding-integer-in-c/ explains the essence of this. '1' and '0' are (usually) next to each other so '1' - '0' is 1, '2' - '0' is 2... – doctorlove Jul 07 '17 at 15:10
  • Try it and you'll see that it won't work. Debug it and you'll understand why it won't work. – Jabberwocky Jul 07 '17 at 15:16
  • 1
    @doctorlove-- note that since a particular character encoding is not specified in the Standard, adjacent characters of the Latin alphabet, e.g, need not be encoded in a contiguous sequence; you seem to be referencing this fact. [Yet, the Standard _does_ require that the characters `0,..., 9` be encoded in a contiguous sequence.](http://port70.net/~nsz/c/c11/n1570.html#5.2.1p3) So, `1` and `0` are _always_ next to each other. – ad absurdum Jul 07 '17 at 15:25
  • Cool - I learnt something – doctorlove Jul 07 '17 at 16:13
  • I apologize for my duplicate question and this code works for me. – Surya Elavazhagan Jul 09 '17 at 16:43

1 Answers1

1

It is basically taking the second character in str (remember arrays are zero based) and assuming it will be in the range '0'..'9'. For this reason, it is later subtracting the ascii code of '0'

This will only work for a single character and it is not a replacement for atoi

Juan Leni
  • 6,982
  • 5
  • 55
  • 87