c++字符串转整数问题
字符串转整数的过程中,为什么下面的第一个代码是正确的,而第二个代码的结果是错误的,这是为什么啊,有知道的小伙伴吗,非常感谢。
正确:
int getDay(string str)
{
int a = 1000 * (str[0] - '0');
int b = 100 * (str[1] - '0');
int c = 10 * (str[2] - '0');
int d = str[3] - '0';
int year = a + b + c + d;
cout << year << endl;
}
错误:
int getDay(string str)
{
int year = 1000 * (str[0] - '0')+100 * (str[1] - '0')+10 * (str[2] - '0')+str[3] - '0';
cout << year << endl;
}