Thread: Formula string conversion

  1. #1
    Registered User
    Join Date
    Mar 2002

    Formula string conversion

    Im writing a program in which i would like the user to be able to enter a formula then have the formula calculated. The only way i can think of doing this is to have the formula imputted into a string, then use a switch and some loops to execute the formula. Is there a library or a more elegant method to do this?

    Thak you,

  2. #2
    I'm pretty sure there is no simple way to do this, but with classes/objects you would be able to do it probably in a cool way.

  3. #3
    have the user enter the expression in postfix

    char array[MAX];
    char ch;
    int i=0;
    while (ch=(char) getc(stdin)){
    int pop(int a)
    return array[a];
    void push(int b)

    the basic idea is this: if the element is a number, pop it from the stack. If it is an operand, then add/sub/mult/divide the two numbers popped from the stack and push the result.

    Here is an example: 67+12++ (this is 6+7+1+2)
    the program pops 6 and 7, sees the +, adds 6+7, and pushes 13 so the resulting expr is 1312++, which evaluates to 133+, which evaluates to 16.

    In reality it is harder, because you will have to deal with conversions. Also, it is nice if you incorporate the whole thing into a struct or class, and make pop and push private functions. That way it is easier to have a countvar that keeps track of where you are in the stack.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  5. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 11:40 AM