1

I was trying to make a calculator in the Rust programming language. The calculator performs basic arithmetic operations like add, sutract, exponent etc. The challenging part for me is that the user input is a String and I want the calculator to be intelligent enough so that when the user types 3 + 1 on console it will return 4 or 2^3 = 8. I can parse the String into an integer or any other data type, but how can I convert "+" into the arithmetic operator?

Taimoor
  • 67
  • 8
  • 2
    Welcome to Stack Overflow! This doesn't (I don't think) directly answer your question, but you may want to look at the [shunting-yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) for parsing arithmetic expressions like `3 + 1`. – trent Dec 03 '19 at 18:37
  • thanks that really helped to make a logic for the problem. – Taimoor Dec 03 '19 at 18:55

1 Answers1

3

you can use a crate named meval and just pass the string to the eval_str function

use meval::eval_str;

fn main() {
    let r = meval::eval_str("1 + 2").unwrap();
    println!("1 + 2 = {}", r);
}
omrihhh
  • 79
  • 4