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

C++ 将字符串元素转换为整数(C+;+;11),c++,string,c++11,type-conversion,integer,C++,String,C++11,Type Conversion,Integer,我尝试使用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 f

我尝试使用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;
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串s=“1 2 3 4 5”;
//打印数字的平方
对于(int i=0;istd::string
,cout
stoi()
可以正常工作。 所以

因为,这里传递的是一个
char
,所以可以使用以下代码行来代替for循环中使用的代码行:

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

std::cout问题是
stoi()
不能与
char
一起使用。或者,您可以使用
std::istringstream
来执行此操作。另外
std::pow()
接受两个参数,第一个是基,第二个是指数。您的注释表示数字的平方,因此

#include <sstream>

string s = "1 2 3 4 5 9 10 121";

//Print the number's square
istringstream iss(s);
string num;
while (iss >> num) // tokenized by spaces in s
{
    cout << pow(stoi(num), 2) << endl;
}
#包括
字符串s=“1 2 3 4 5 9 10 121”;
//打印数字的平方
istringstream iss(s);
字符串数;
while(iss>>num)//由s中的空格标记
{
cout类似于:

#include <cmath>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";
    istringstream iss(s);
    while (iss)
    {
        string t;
        iss >> t;
        if (!t.empty())
        {
            cout << pow(stoi(t), 2) << endl;
        }
    }
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串s=“1 2 3 4 5”;
istringstream iss(s);
while(国际空间站)
{
字符串t;
iss>>t;
如果(!t.empty())
{

问题是
s[i]
显然是一个
char
。一个字符。现在看看
stoi
()的参数必须是什么,你应该能够自己计算出来。
stoi
std::string
(和
std::wstring
)一起工作,但是
s[i]
是一个
char
。如果我使用
substr
函数,它会工作吗?因为从我读到的,它返回字符串类型?@AkhmadZaki是的,
substr
会工作。如果s包含一个大于9的数字怎么办?是的,我忘了包含指数。谢谢你的回答。上面的代码对于数字大于1的整数仍然有效吗?@AkhmadZak是的,最好使用
std::istringstream
而不是
std::stringstream
,这样编译器就可以检测到意外的
,谢谢你的回答。只要字符串中的每个字符都在
'0'
'9'
的范围内,这个技巧就可以保证有效。字符串中只有一个空格,你就有可能失去它定义的行为。它也更难阅读。这一个应该被工程上的答案所接受。谢谢你的答案。
#include <sstream>

string s = "1 2 3 4 5 9 10 121";

//Print the number's square
istringstream iss(s);
string num;
while (iss >> num) // tokenized by spaces in s
{
    cout << pow(stoi(num), 2) << endl;
}
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";
    istringstream iss(s);
    while (iss)
    {
        string t;
        iss >> t;
        if (!t.empty())
        {
            cout << pow(stoi(t), 2) << endl;
        }
    }
}