如何将字符串中的空格分隔数字序列转换为整数

问题描述 投票:0回答:3

我正在尝试使用 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;

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

c++ string c++11 type-conversion integer
3个回答
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
投票
如果您使用

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";

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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.