You need to create a well-known data structure called "
expression tree". A node of a tree should represent an expression and it should have 0, 1 or 2 child nodes representing sub-expressions. The node should be of one of few different classes derived from the common abstract class, let's call this class "Expression". Each terminal derived class representing a node should represent a concrete mathematical operator, like − or +. You need to define some virtual functions used to transform the sub-trees (sub-expressions) under each node, according to the algebra you are going to define. These function should be overridden in each derived class. This way, you will be able to do the operations on the tree based on defined operations on the sub-trees, recursively.
In other words, you should define the
algebra over the C++ tree structure made of the node (expression) classes I mentioned above and the mapping between this algebra and some traditional mathematical algebra you need to cover in your calculations. Naturally, these two algebras should be isomorphic, and the mapping should be the on-to-one correspondence.
After that, you should develop the method to "output" the expression in the form of text, pretty much like the one you've shown. You can also consider support of HTML, XML, and, in particular, MathML, for most advanced option, or some notation of your own. I'm not sure you need it, but this is something you better be aware of:
http://en.wikipedia.org/wiki/MathML[
^].
And finally, the procedure if population of the
expression tree will need to be developed as some kind of parsing. You may need to learn some theory of parsers or… not, as you can do it all by yourself. Anyway, if you feel a need to learn this area, this is a good place to start:
http://en.wikipedia.org/wiki/Parsing_expression_grammar[
^].
To learn more of expression trees, please see:
http://en.wikipedia.org/wiki/Expression_tree[
^].
They are widely used at least in two areas: in
compilers from a computer languages and, more closely to our topic, in
computer algebra systems:
http://en.wikipedia.org/wiki/Compiler[
^],
http://en.wikipedia.org/wiki/Computer_algebra_system[
^].
Please also see my answer and other answers to this question:
Reduce equation with c#[
^].
The computer algebra systems is something you need to learn, but, in my opinion, general mathematical and programming culture and a reasonably good brain in one's head would be enough to develop such system on your own, especially in case when it does not have to be most comprehensive in the world. As you can see, most of the knowledge you would need is a commonplace pretty well covered by Wikipedia.
Wish you the best of luck,
—SA