so i have been tasked with creating a c++ calculator that takes user input as a string equation like "-2.5 + 40 - 3 * 8 / 2) which would read from left to right(order of operations not followed) and output 138 as the answer. there has to be spaces between each operator and operand.
ive made a calculator, but it only works on single digit positive integers. here is the code.
#include <iostream>
#include <string>
float calculator(string input){
float result = 0;
for(int i = 0; i < input.length(); i++){
if(input[i] == '+'){
result += (input[i-2]-'0') + (input[i+2]-'0');
}
return result;
}
int main(){
string input = "";
cout << "enter string" << endl;
getline(cin, input);
cout << calculator(input) << endl;
so inputting "1 + 3" gives 4 but "12 + 3" yields 5. i know why it is giving 5 i just don't know how to fix it. i don't want anyone to just plain give me the answer, but if someone could point me in the right direction? i thought maybe using the regular cin instead of getline because that would read up to a space and store it, but couldn't really think of how to continue this.
with your guys pointers, i made another calculator that uses cin>>. but it only works if i give exactly the right amount of operators and operands, which is not possible to know if I'm receiving random user equations. any ideas?
int main(){
float num1 = 0, num2 = 0, num3 = 0, answer = 0;
char op1, op2;
cout << "enter string\n";
cin >> num1;
cin >> op1;
cin >> num2;
cin >> op2;
cin >> num3;
if(op1 == '/'){
answer = num1/num2;
}
if(op1 == '*'){
answer = num1*num2;
}
if(op1 == '-'){
answer = num1-num2;
}
if(op1 == '+'){
answer = num1+num2;
}
cout << "answer is " << answer << endl;
return 0;
}