小编Duc*_*yen的帖子

我的“stoi”函数或编译器有问题吗?

我尝试编写一个函数将一串数字转换为整数。当我使用 g++ 9.2.0 在 VS 代码上运行我的代码时,我得到了错误的输出,但是当我在 repl.it 上运行它时,我得到了正确的输出。这是我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是 …

c++

1
推荐指数
1
解决办法
105
查看次数

标签 统计

c++ ×1