-
Help understanding code
I found this code on the internet and I don't understand whats the point of this line : (str[i] - '0')
I know its not working without it but whats the point of subtracting 0 of something?
Code:
#include <string>
#include <iostream>
using namespace std;
int string2sec(const std::string& str)
{
int i = 0;
int res = -1;
int tmp = 0;
int state = 0;
while(str[i] != '\0')
{
// If we got a digit
if(str[i] >= '0' && str[i] <= '9')
{
tmp = tmp * 10 + (str[i] - '0');
}
// Or if we got a colon
else if(str[i] == ':')
{
// If we were reading the hours
if(state == 0)
{
res = 3600 * tmp;
}
// Or if we were reading the minutes
else if(state == 1)
{
if(tmp > 60)
{
return -1;
}
res += 60 * tmp;
}
// Or we got an extra colon
else
{
return -1;
}
state++;
tmp = 0;
}
// Or we got something wrong
else
{
return -1;
}
i++;
}
// If we were reading the seconds when we reached the end
if(state == 2 && tmp < 60)
{
return res + tmp;
}
// Or if we were not, something is wrong in the given string
else
{
return -1;
}
}
int main()
{
std::cout << string2sec("01:01:05") << std::endl;
// std::cout << string2sec("1:01:01") << std::endl;
// std::cout << string2sec("1:2:0") << std::endl;
// std::cout << string2sec("10:10:10") << std::endl;
return 0;
}
-
That's not a zero, that's the character code of '0', which in ASCII is 48, and all of the digits are in order ('1' is 49, '2' is 50, ..., '9' is 57). To append a digit to tmp, you multiply it by 10 and then add that digit to it. If you don't subtract '0', you would add an extra 48 instead which you don't want.
-
Thank you.
So then why when I do this it wont change the value of str?
Code:
string str = "103";
cout << "result: " << str[0] - '0' << "\n\n";
cout << "result: " << str[1] - '0' << "\n\n";
cout << "result: " << str[2] - '0' << "\n\n";
-
Why would it? You're not assigning anything, you're just doing the subtractions.
-
When you do str[0] - '0', I believe the result is automatically promoted to an int, and when you send that int value to cout it's converted to its text representation, so you'll see "1", "0", and "3" printed.
Try assigning 0 to an int variable and print it out, and then assign '0' to the variable and print it out.