### c++ Calculator: Making the program sense the sign used

I have this code but i would like it to ask the user to enter the Equation then the program will sense what Operator(+/*-) they want. A sample input would be 7+8 i want the program to be able to detect the sign. How would i go about doing this?

 ``1234567891011121314151617181920212223242526272829303132333435`` ``````#include using namespace std; void main () { double Number_1 = 0; double Number_2 = 0; char Operator = 'a'; cout<<"Enter First Number: "; cin>>Number_1; cout<<"Enter Second Number: "; cin>>Number_2; cout<<"Enter the Operator: "; cin>>Operator; switch (Operator) { case '+': cout <<"Result: "<
Last edited on
 ``123456789101112131415161718192021222324252627282930313233343536373839404142`` ``````#include #include using namespace std; void main () { //1. Store the input in a string string input; cin >> input; //2. Parse the string for the operator string::size_type position = input.find_first_of("+-*/"); if (position != string::npos) //operator found? { double Number_1 = 0; double Number_2 = 0; char Operator = input[position]; //3. Get the first number Number_1 = atof(input.c_str()); //4. Get the second number Number_2 = atof(input.substr(position+1).c_str()); //5. Calculate ... switch (Operator) { case '+': cout <<"Result: "<
You'd have to parse the character sequence of the equation, one character at a time, and then determine the number of variables and the operations the equation involves. Since the length of the equation may vary ("7+8" , "7+8-(6+11)*5" etc), your equation string parser would have to be recursive, so that it can penetrate and parse any number of brackets, sequence of operations, number of required variables etc. .

When parsing, you'd have to read a character, determine if it's a digit (in which case it would have to be stored as a variable), an operator (in which case it determines the operation to be applied to the previously read number), a bracket (in which case the content of the bracket should be calculated independently of the operators applied outside of the bracket, probably by means of a recursive function that returns a numerical value -- perhaps a double). Also make sure to calculate multiplication and division operations prior to addition and subtraction operations if no brackets are specified, etc. All this should be done by parsing the equation character-by-character and determining the series of operations. The parsing continues until the end of the string is reached, in which case you may want to perform some checks to make sure that no open brackets or unhandled operators remained without being used (which may be due to incomplete or erroneous user input, like "7-(", "7+", "7+*" etc), before outputting a result.
Last edited on
Topic archived. No new replies allowed.