I tried writing a function to convert a string of numbers to an integer. I get a wrong output when I run my code on VS code with g++ 9.2.0 but when I run it on repl.it, I get a right output. This is my code:
#include <iostream>
#include <cmath>
using namespace std;
int charToInt(char c)
{
return c - '0';
}
int myStoi(string s)
{
int r = 0, len = s.length();
for (int i = 0; i < len; i++)
{
r += charToInt(s[i]) * pow(10, len - i - 1);
}
return r;
}
int main()
{
string str = "123";
cout << stoi(str) << endl;
cout << myStoi(str) << endl;
return 0;
}
This is the output on VS code:
PS C:\Users\ASUS\Code\Practice> g++ .\convertChartoInt.cpp
PS C:\Users\ASUS\Code\Practice> .\a.exe
123
122
And this is the output on repl.it:
./main
123
123
I try to figure out why I get the number 122 on VS code, so I cout value of r
in myStoi
function:
for (int i = 0; i < len; i++)
{
r += charToInt(s[i]) * pow(10, len - i - 1);
cout << r << " ";
}
Here is the result:
PS C:\Users\ASUS\Code\Practice> .\a.exe
99 119 122
I think the first number should be 100 in order to generate a right output but it returned 99, can anyone tell me what this bug is and how to fix it? Thanks!