Self-function that convert string into integer value
Hello, I wonder why this function doesn't work all the time depending on the length of the parameter : have look at this code : #include <iostream> #include <string> #include <math.h> using namespace std; int to_integer(string x){ int ret = 0; int i2 = pow(10, x.length()); for(int i = 0; i < x.length(); i++){ switch(x[i]){ case '1': ret += i2 * 1; break; case '2': ret += i2 * 2; break; case '3': ret += i2 * 3; break; case '4': ret += i2 * 4; break; case '5': ret += i2 * 5; break; case '6': ret += i2 * 6; break; case '7': ret += i2 * 7; break; case '8': ret += i2 * 8; break; case '9': ret += i2 * 9; break; case '0': break; default: return 0; } i2 /= 10; } return ret/10; } int main() { int integer; integer = to_integer("66432"); //this one works cout<<integer<<endl; integer = to_integer("6643"); // this one doesn't work ! cout<<integer<<endl; return 0; } /* OUTPUT : 66432 6641 */ Any idea ?? I know it exists fucntions that can handle this but I am trying to make my own to enhance my skill. thx