Understanding of String.at() - '0';

Hi can anyone help me with this code?

int day;
 
day = (((int)UserInput.at(0) - '0') *10) + (int)UserInput.at(1) - '0';


I have no idea why does it need a -'0' after casting a string to int, does anyone know why and kind enough to explain to me ?
The reason is that UserInput.at(1) is returning a single ascii character, which when cast to int probably has a value around the 50s. Seeing as I presume you want to convert '0' to 0 and '1' to 1 etc, the character value of 0 is taken off the character value retrieved from the string. The value of '0' is 48 and '1' is 49 and they increase sequentially, so taking off 48 ('0') converts the ascii value of a number to its actual value.
Last edited on
UserInput.at(0) returns the ASCII code for the first character in the string. The problem is that the ASCII code for the character '0' is NOT zero, it's 48. Character '1''s ASCII code is 49 etc. So to convert a character value to it's numeric equivalent, you have to subtract 48. The clearest way to do that is to subtract '0', which will work even if the computer isn't using ASCII encoding (which is very rare these days).
thanks for the information now I understand that the position of the string which contain the value is stored as ascii code, but I still doesn't know where does the 0 comes from in the value.
Lets say '1' in ascii code represent 49, by minus the '0' away from the ascii it became 1, the question is where does the '0' taken away from in 49???

1
2
3
4
string UserInput;
int day;
std::getline(cin, UserInput);
day = (((int)UserInput.at(0) - '0') *10) + (int)UserInput.at(1) - '0';
I'm not sure I entirely understand your question, but let me try and explain again, because I think you've got it the wrong way round.
If UserInput = "01", then in actuality, that is stored as the numbers 48 49.
When you get the first character (via .at(0)) it is '0'. When this is cast to int, it is 48. This is because the offset of the numerical characters in the ascii set is 48. Therefore you have to take off the numerical value of the character '0', which is 48. Basically, in order to convert the numerical characters into numbers, you have to find out how far they are in the ascii series away from '0', as the numerical characters are stored sequentially, '1' is one unit away from '0', '2' is two units away from '0' and so on.
OMG thank you so much now I understand why we need to - '0' because 'zero' in ascii value is 48 therefore 49-48 = 1 it return 1.
Topic archived. No new replies allowed.