There are three things confusing you here.
First the expressions:
i1 = data[0];
i2 = data[p1];
Assign the character values of data[0]
and data[p1]
If the input is 2+4
you’re actually assigning the character values of ‘2’ and ‘+’. In ASCII “2” is represented by code-point 50 and “+” by 43.
So then the expression i1+i2
actually equals 93.
What is also confusing you is that s=i1+i2
actually binds to the overloading basic_string& operator=( CharT ch );
and so converts 93 back to a character and assigns a singleton string to s
which happens to be ]
as you see!
This is your code with those three faults fixed:
#include <iostream>
using namespace std;
int main()
{
string input;
int length;
int p1;
int i1;
int i2;
string result;
cout << "Enter your expression" << endl;
cin >> input;
length = input.size();
char data[length];
input.copy( data, length );
switch(data[1]){
case '+' : p1 = length - 1; //Not -2 as was.
i1 = data[0]-'0';//Works for ASCII compatible and so all modern systems...
i2 = data[p1]-'0';
result = std::to_string(i1 + i2);//Force the creation of a decimal string of the result.
cout << result << endl;
break;
}
return 0;
}
5
solved Why doesn’t the char convert to an int?