Converting string to int,operators,etc.

This came up while i was working on my calculator and I trying to come up with an easier way to do it. Is it possible to convert a string, entered by the user, into integers mathematical operator etc?

For example could I take

"5 times 3", "3 x 5", "square root of 25"

and then convert that string into the proper integers and operators? However I'm just unsure of how to do this. Any advice?
To convert a std::string to an int use std::string::stoi().
http://www.cplusplus.com/reference/string/stoi/
scanf() used to be good for this, the count only works if the literal text also matches :) so the below example fails to find "times by" and continues on even though both scans are looking for 2 values...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;


int calc(char source[])
{
  int count, x, y;
  count = sscanf(source,"%d times %d",&x,&y);
  if (count == 2)
     return x*y;

  count = sscanf(source,"%d multiplied by %d",&x,&y);
  if (count == 2)
     return x*y;
     
  count = sscanf(source,"%d x %d",&x,&y);
  if (count == 2)
     return x*y;
     
  count = sscanf(source,"square root of  %d",&x);
  if (count == 1)
     return sqrt(x);
}


int main()
{
    cout << calc("5 multiplied by 4") << endl;
    cout << calc("5 times 4") << endl;
    cout << calc("5 x 4") << endl;
    cout << calc("square root of 100") << endl;
 
    return 0;
}


EDIT: replaced with more complete solution
Last edited on
wait wait wait... I got an even crazier idea. What about turning the string into an Array. Then using a for statement and a variety of switch( of if else statements). It might be easier to do ?
you could create a parser.

once upon a time i used flex and bison, it can get deep but works well.
http://flex.sourceforge.net/
https://www.gnu.org/software/bison/

for simple expressions I doubt you'll find anything as straight forward and fast as what I posted, but consider "5 multiplied by 23 over 4 divided by (9 raised to the power of 10) and the parser starts to look like a good solution.

if you enforce parenthesis you can use something like what i posted quite easily.
"(5 multiplied by (23 over 4)) divided by (9 raised to the power of 10)"

recurse the parenthesis, pass the innermost to calc() first then work your way out.

This sounds fun! I'm off to bed before i get carried away :)

Is this for a speech engine calculator? I.e. Dragon NaturallySpeaking?

I'm just a beginner, but… Sounds a bit complicated for a beginner forum, isn't it?
Whoa, speech to text is a little far out there. Also Dragon is a great program. I'm trying more of a computer reading text and using the order of operation. All that good stuff.
Topic archived. No new replies allowed.