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

5

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

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


1
问题在于s[i]显然是一个char,只有一个字符。现在看一下stoi()的参数应该是什么,你应该能够自己想出来。 - Sam Varshavchik
1
stoi 可以处理 std::string(和 std::wstring)类型,但是 s[i] 是一个 char 类型。 - songyuanyao
如果我使用 substr 函数,它能正常工作吗?因为根据我所读的,它返回字符串类型。 - Akhmad Zaki
1
@AkhmadZaki 是的,substr 可以工作。 - Arne Vogel
你确定你的整数需要以字符串的形式吗?如果可能的话,最好使用整数数组。 - undefined
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时会出现问题,所以进行了编辑。


如果 s 包含一个大于 9 的数字,会怎么样? - Sid S
是的,我忘记包括指数了。感谢您的答案。 - Akhmad Zaki
以上代码对于位数大于1的整数仍然有效吗? - Akhmad Zaki
@AkhmadZaki 是的,它可以。 - Justin Randall
1
最好使用std::istringstream而不是std::stringstream,这样编译器可以检测到意外的<< - Christian Hackl

1
"

stoi()在使用std::string时运行良好。所以,

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

会输出:
12346

由于您在for循环中传递了一个char,因此可以使用以下代码行代替您在for循环中使用的代码行:

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

感谢您的回答。 - Akhmad Zaki
1
这个技巧只有在字符串中的每个字符都在“0”到“9”的范围内时才能保证有效。如果字符串中有一个空格,就会出现未定义的行为。而且这种写法更难阅读。 - Christian Hackl
1
这个答案应该以工程方式被接受。 - cinqS

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

感谢您的回答。 - Akhmad Zaki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接