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

时间:2018-01-06 03:49:29

标签: 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
    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;

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

3 个答案:

答案 0 :(得分:2)

问题是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中大于单个数字的数字,因为for循环方法会中断大于9的数字。

答案 1 :(得分:1)

如果您使用stoi()

std::string可以正常工作。 所以,

string a = "12345";
int b = 1;
cout << stoi(a) + b << "\n";

输出:

12346

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

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

答案 2 :(得分:0)

类似的东西:

#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;
        }
    }
}