Convert string element to integer (C ++ 11)

I am trying to convert a string element to an integer using a function stoiin C ++ 11 and use it as a parameter for a function pow, for example:

#include <cstdlib>
#include <string>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";

    //Print the number square
    for(int i = 0; i < s.length(); i += 2)
    {
        cout << pow(stoi(s[i])) << endl;
    }
}

But I have this error:

error: no matching function for call to 
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;

Does anyone know what the problem is with my code?

+4
source share
3 answers

The problem is that stoi()it will not work with char. Alternatively you can use std::istringstreamfor this. It also std::pow()takes two arguments, the first of which is the base, and the second is a measure. Your comment says the square of the number is so ...

#include <sstream>

string s = "1 2 3 4 5 9 10 121";

//Print the number square
istringstream iss(s);
string num;
while (iss >> num) // tokenized by spaces in s
{
    cout << pow(stoi(num), 2) << endl;
}

, , , s, for , 9.

+2

stoi() , std::string. ,

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

:

12346

char, , for:

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

Sort of:

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

Source: https://habr.com/ru/post/1691818/


All Articles