I am trying to convert string element to integer using stoi
function in C++11 and using it as parameter to pow
function, like this:
#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;
}
}
But, i got an error like this:
error: no matching function for call to
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;
Anyone know what is the problem with my code?
The problem is that stoi()
will not work with char
. Alternatively you can use std::istringstream
to do this. Also std::pow()
takes two arguments the first being the base and the second being the exponent. Your comment says the number's square so...
#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;
}
Edited to account for numbers larger than single digit in the original string s, since the for loop approach breaks for numbers larger than 9.
stoi()
works fine if you use std::string
.
So,
string a = "12345";
int b = 1;
cout << stoi(a) + b << "\n";
Would output:
12346
Since, here you are passing a char
you can use the following line of code in place of the one you are using in the for loop:
std::cout << std::pow(s[i]-'0', 2) << "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With