Thread: Reading formula from a file

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    33

    Reading formula from a file

    This isn't so much C++ related as it is to making a general algorithm, but since the program will be written in C++ I decided to post it here.

    Basically, the program needs to read a text file which contains a mathematical formula.

    It is formatted like this:

    Input file example: For 3*x will look like

    *
    3
    x

    Input file example: For (7*(5*x))^2

    ^
    *
    7
    *
    5
    x
    2

    Every equation will have a variable x in it somewhere.

    Basically what I am trying to figure out is how I can transform the input into formula form.

    I have heard this is how compilers (csc in C# at least) translate formulas in the first place, and have done on paper examples of how to move from one form to the other. If so, does anyone remember what it is called so I can do some reading on it?

    What the program will do is if the text file has:
    *
    3
    x

    It will print 3 * x, and then ask the user to input an x and provide the product.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    That's Polish notation (a/k/a prefix notation), is what that is. You can easily build an expression tree out of it.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    33
    Okay I think I understand that part, but when I want to print the formula in infix notation how can I know when to print the parenthesis???

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You print a parenthesis when a lower-precedence operator is a child of a higher-precedence operator, or when an operator is a right child of an equally-precedent operator. (For instance, 7 - (4-2) would have the second subtraction as the right child of the first; while 7 - 4 - 2 would have the second subtraction at the root, and the first subtraction as the left child.)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM