简体   繁体   中英

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?

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

Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM