Self-function that convert string into integer value | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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

23rd Dec 2017, 3:57 PM
Christopher Milazzo
Christopher Milazzo - avatar
5 Answers
0
@ipang I replaced the line : int i2 = pow(10, x.length()); with : float i2 = pow(10, x.length()); and I don't know why exactly but it worked !
23rd Dec 2017, 7:05 PM
Christopher Milazzo
Christopher Milazzo - avatar
+ 5
You will be better to create your own implementation of pow function specifically designed for integers, I faced quite a similar problem when I need to collect and convert numerical string into number. Here's my code for that purpose, you can see there's a function named mpow. https://code.sololearn.com/cTskcyl6ckvX/?ref=app Hth, cmiiw
23rd Dec 2017, 4:36 PM
Ipang
+ 3
Have you tried using float or double to receive the return value from pow function? in my case, when I wrote this, I found that some numerical string gave me incorrect results, probably because pow return floating point while the receiving variable is an int, possibly the rounding of the fractal points was the cause (no solid proof though).
23rd Dec 2017, 6:24 PM
Ipang
+ 3
Then we may have had the same story : ) Anyways, I'm glad you get your code to work, good job!
23rd Dec 2017, 7:09 PM
Ipang
0
Thank you for this code, i learned a lot with it. I am still wondering what's wrong with mine tho :D
23rd Dec 2017, 6:09 PM
Christopher Milazzo
Christopher Milazzo - avatar