将字符串元素转换为整数(C++ 11)

Akh*_*aki 5 c++ string integer type-conversion c++11

我试图使用stoiC++ 11中的函数将字符串元素转换为整数并将其用作pow函数的参数,如下所示:

#include <cstdlib>
#include <string>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";

    //Print the number's square
    for(int i = 0; i < s.length(); i += 2)
    {
        cout << pow(stoi(s[i])) << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我得到了这样的错误:

error: no matching function for call to 
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;
Run Code Online (Sandbox Code Playgroud)

有人知道我的代码有什么问题吗?

Aru*_*ava 1

stoi()如果你使用的话,效果很好std::string。所以,

string a = "12345";
int b = 1;
cout << stoi(a) + b << "\n";
Run Code Online (Sandbox Code Playgroud)

会输出:

12346
Run Code Online (Sandbox Code Playgroud)

因为,在这里您要传递 a ,char您可以使用以下代码行代替 for 循环中使用的代码:

std::cout << std::pow(s[i]-'0', 2) << "\n";
Run Code Online (Sandbox Code Playgroud)