-4

I am trying to push a integer that is stored in a string to a stack of type int I was trying to do the same by using stack.push(str[i]) which resulted in some weird values in the final outcome

Github copilot suggeted to do it this way which was succesfull

else
       {
           temp.push(exp[i]-'0');
       }

what is the meaning of -'0' here

  • 2
    Likely a dupe of [Convert char to int in C and C++](https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c), but you haven't provided a [mcve], so it's hard to tell what you are talking about. – Yksisarvinen Sep 04 '22 at 19:10
  • 5
    This should be explained, somewhere, in every C++ textbook. "github copilot" is not a replacement for a C++ textbook. – Sam Varshavchik Sep 04 '22 at 19:17

1 Answers1

3

The char '0' has ascii value 0x30 (48 decimal).

The char '9' has ascii value 0x39 (57 decimal).

If you do '9' - '0' = 57 - 48 = 9.

So you are converting a digit from its ascii number '9' = 57 to its numeric value 9.

This is often used when fast-converting a string of integers to its numeric value.

Something Something
  • 3,999
  • 1
  • 6
  • 21