Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string element to integer (C++11)

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?

like image 490
Akhmad Zaki Avatar asked Oct 17 '22 00:10

Akhmad Zaki


2 Answers

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.

like image 97
Justin Randall Avatar answered Nov 09 '22 06:11

Justin Randall


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";
like image 45
Arunava Avatar answered Nov 09 '22 06:11

Arunava