converting char to an int

so iv been doing alot of looking on how to do this i see atoi alot but just donst seem to work form me



bool ope(char op)
{
if (op=='+' || op=='-' || op=='/' || op=='*' || op=='^'){
return true;
}
else{
return false;
}
}

int calculate(string p)
{
char first;
char second;
int sum;
int f;
int s;
for(int i=0; i< p.length();i++){

if(ope(p[i])==true){
first = p[i-2];
second = p[i-1];

f= atoi(first); <---- what to convert first to and int
s= atoi(second);< ----- what to convert second to and int

if(p[i]=='*'){
sum = first *second;
}
if(p[i]=='/'){
sum = first / second;
}
if(p[i]=='+'){
sum = first + second;
}
if(p[i]=='-'){
sum = first - second;
}


}


}

}
atoi takes a const char* as a parameter, not a char.

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <cstdlib>

int main() {
        const char* foo = "21";
        std::cout << atoi(foo) << std::endl;
        return 0;
}
then what do i want to use if the char isnt const my first and second will be changing, since its going thru an array.
You don't need atoi for this case. Atoi expects a const char* as seen here:

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

A few options:

f = (int)first;
s = (int)second;


You could also use a static cast like so:

f = static_cast<int>(first);
s = static_cast<int>(second);

Many compilers don't even require an explicit cast from char to int so this should work as well:

f = first;
s = second;
you can use atoi by passing the address because it expects a pointer:

f= atoi(&first);
s= atoi(&second);
Topic archived. No new replies allowed.