confused about atoi getting the wrong value

so i have a char array p =[ 1,2,+]
when i store those values using the atoi i get all the right values but the 1st one for example

int s;
s=atoi(&p[0]);
the value should be 1 but i get 12
s=p[1] i get 2 like i should

another example

lets say p=[4,6,-]

s=atoi(p[0]); should equal 4 but i get 46
Last edited on
Give us a complete example, please.
atoi takes a c string as argument. If you do like this:
1
2
char p[] = "12";
int s = atoi(&p[0]);
s will get value 12 because &p[0] gives you a pointer to a c string with content "12".

&p[1] gives you a pointer to the '2' in the c string so it will be treated as a c string with content "2" and this code
s = atoi(&p[1]);
will give s value 2.
so now i understand what happen, what do i got to do if i wanna to get 1 for the value instead of 12?
here is the full exmaple , got to ccaluate postfix equation

int calculate(string p)
{
char postfix[p.length()];// char array store the values of p in it
int calc [p.length()];
int count=0;
int first;
int s;


// asigned the values of p to the array postfix
for(int j=0; j< p.length();j++){
postfix[j]=p[j];

}

// for the length of p[i] adds p to calc array until an operator is found
for(int i=0; i<p.length() ;i++){

// if statement if p[i]== a value goes into calc array
if(ope(p[i])==false){

s = atoi(&postfix[i]);
calc[count]=s;

count++;
}

// if statmetns if p[i] == opetor then pulls the last to digits and use
// that operator
if(ope(p[i])==true){

if(p[i]=='^'){
a=calc[count-2];
b=calc[count-1];
calc[count-2]=0;
calc[count-1]=0;
count=count-2;
calc[count]=pow(a,b);
count++;
}
if(p[i]=='*'){
a=calc[count-2];
b=calc[count-1];
calc[count-2]=0;
calc[count-1]=0;
count=count-2;
calc[count]=a*b;
count++;
}
if(p[i]=='/'){
a=calc[count-2];
b=calc[count-1];
calc[count-2]=0;
calc[count-1]=0;
count=count-2;
calc[count]=a/b;
count++;
}
if(p[i]=='+'){
a=calc[count-2];
b=calc[count-1];
calc[count-2]=0;
calc[count-1]=0;
count=count-2;
calc[count]=a+b;
count++;
}
if(p[i]=='-'){
a=calc[count-2];
b=calc[count-1];
calc[count-2]=0;
calc[count-1]=0;
count=count-2;
calc[count]=a-b;
count++;

}
}
}
sum=calc[0];

return sum;
}
In your original post did you mean

so i have a char array p =[ 1,2,+]


or did you really mean

so i have a char array p =[ '1','2','+']


Assuming you meant the latter, you can simply do:

s = p[0] - '0'

Topic archived. No new replies allowed.