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

Convert string element to integer (C++11)

本文关键字:C++11 整数 字符串 元素 转换      更新时间:2023-10-16

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

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

问题是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 的数字。

如果您使用std::stringstoi()可以正常工作。 所以

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

将输出:

12346

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

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

像这样:

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