1

I am getting an odd error in my code where I try to take the elements of a std::string and convert them into 2 seperate ints

An example of the string would be "A6". I would like to be able to convert this string into 2 integers. In this example, the integers would be 65 (because 'A' is 65 in the ASCII chart) and 6.

Currently this is the code:

    // Parse string into integers
    int tempRow = userGuess[0];
    
    int tempColumn = userGuess[1];

    std::cout << tempRow << tempColumn;

"A1" outputs 65 and 49. Why does '1' become an integer of 49?

RudyGoburt
  • 291
  • 1
  • 11

1 Answers1

1

The ascii code for 1 is 49, which is the result you are assigning to tempColumn. If you want the integer value, you need to do:

int tempColumn = userGuess[1] - '0';

This subtracts the ascii version of 0 which is 48 from the integer.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • Thanks. What's the logic behind subtracting '0'? – RudyGoburt Aug 07 '20 at 19:25
  • The ascii values of `0`, `1`, `2`, is 48, 49, 50 etc. Subtracting `0` gives you the result 0, 1, 2, etc. – cigien Aug 07 '20 at 19:27
  • @RudyGoburt Specifically, one of the few requirements that C++ has about legal character sets is that the digits `'0'` through `'9'` must be represented by consecutive values. The character `'0'` has some value, then `'1'` is required to be the value after `'0'` (or `'0' + 1`), `'2'` is one after that (or `'0' + 2`), etc. So no matter what encoding your platform uses, subtracting `'0'` from any of the 10 digit characters will always give you that digit's numeric value. – François Andrieux Aug 07 '20 at 19:48