I need to parse input from a user that could be any number of variations:
1+1 4( 3-0 ) =x 1*(3)-8
How do I do this using scanf to get the raw_input, then split out all of the different values and tell either if it is a string ie x = – () or a int?
This is what I was thinking
char * raw_input;
scanf("%s",raw_input);
It takes a array of char and then I just need to split and convert into a single elements. What is the best way of doing the input and (splitting and converting)
Thanks
If you want to write your own code, the best way is to define your expression in form of a grammar. To easily parse the grammar, it’s best to make it simple.
For example, to parse expressions in the form like this (1+(3*4+x)*y)+1, you could write such a grammar:
Then in your program, for every non-terminal in this grammar (the ones on the left of ->), you write one function, like this:
Similarly,
MultiplicationandRestOfMultiplicationwould be written as functions.Where
extract_intandextract_variableare two functions that take the expression and the position on it, go ahead while they are seeing a number (or a letter in theextract_variablefunction) they build the number (variable) from the expression string and return it, setting position to after where they finished.Note: This is not code for copy paste. It is not complete and lacks sufficient error checking. Some details have been omitted and is offered as a solution to teach how simple parsing is done rather than easiest solution.