i have written a program, where you give a string as input. this string should be a normal term e.g. "5 + 3 / 2" and all numbers and operators have to be seperated via a whitespace. the term you can type in should be as long as you want it to be, e.g. "1 * 2 * 5 - 1 * 4 + 1 + 5 + 3 + 3 + 3" should be working too. +, -, * and / are the only operators that are allowed to be used.
i have already got a working code. but it ignores the fact of * and / before + and -. but it does everything else perfectly. the idea is it creates two arrays, one that saves the operators in a char array (called char operators[ ])and the other array saves the integers in a float array (called float values[ ]). then i have this calculation method:
void calc(float values[], char operators[]) {
float res_final;
float res_array[10];
int counter = (sizeof(values) / sizeof(*values));
for (int i = 0; i < getBorder(values); i++) {
if (i == 0) {
res_array[i] = switchFunction(values[i], values[i + 1], operators[i]);
}
res_final = switchFunction(res_array[i], values[i + 2], operators[i + 1]);
res_array[i+1] = res_final;
if (i == getBorder(values)) {
break;
}
}
std::cout << "evaluation of expression is: " << res_final << std::endl;
}
float switchFunction(float val_1, float val_2, char op) {
switch (op) {
case '+': return val_1 + val_2;
break;
case '-': return val_1 - val_2;
break;
case '*': return val_1 * val_2;
break;
case '/': return val_1 / val_2;
break;
}
return 0;
}
well the code is not really pretty, but i couldnt come up with anything more useful. i have so many ideas but it all failed when it comes to the operators. i wanted to define the normal + in '+' and for the rest too, but this wont work.
so if you have any suggestions on how to include point before line or if you have a complete different approach to mine, i would be glad to hear about it :)