我正在尝试使用C++11中的stoi
函数将字符串元素转换为整数,并将其作为参数传递给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;
}
}
但是,我遇到了如下错误:
error: no matching function for call to
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;
有人知道我的代码出了什么问题吗?
s[i]
显然是一个char
,只有一个字符。现在看一下stoi()
的参数应该是什么,你应该能够自己想出来。 - Sam Varshavchikstoi
可以处理std::string
(和std::wstring
)类型,但是s[i]
是一个char
类型。 - songyuanyaosubstr
函数,它能正常工作吗?因为根据我所读的,它返回字符串类型。 - Akhmad Zakisubstr
可以工作。 - Arne Vogel