This question already has an answer here:
- How do you convert char numbers to decimal and back or convert ASCII 'A'-'Z'/'a'-'z' to letter offsets 0 for 'A'/'a' …? 4 answers
The following code basically takes a string and converts it into an integer value. What I don't understand is why the int digit = s[i] - '0';
is necessary. Why can't it work by using int digit = s[i]
instead? What purpose does the -'0'
have?
int main(){
string s = "123";
int answer = 0;
bool is_negative = false;
if (s[0] == '-')
{
is_negative = true;
}
int result = 0;
for (int i = s[0] == '-' ? 1 : 0; i < s.size(); ++i)
{
int digit = s[i] - '0';
result = result * 10 + digit;
}
answer = is_negative ? -result : result;
cout << answer << endl;
system("pause");
}