Thread: reply

  1. #1
    samurai warrior nextus's Avatar
    Join Date
    Nov 2001
    Posts
    196

    reply

    here is alittle excercise i wrote..its sorta a calculator that solves math equations

    Code:
    #include <iostream>                 // For stream input/output
    #include <cstdlib>                  // For the exit() function
    #include <cctype>                   // For the isdigit() function
    #include <string>                   // For the strcpy function
    using namespace std;
    
    void eatspaces(char* str);          // Function to eliminate blanks
    double expr(char* str);             // Function evaluating an expression
    double term(char* str, int& index);   // Function analyzing a term
    double number(char* str, int& index); // Function to recognize a number
    char* extract(char* str, int& index); //Function to extract a substring
    
    const int MAX = 80;         // Maximum expression length including '\0'
    
    int main(void)
    {
       char buffer[MAX] = {0};    // Input area for expression to be evaluated
    
       cout << endl
            << "Welcome to your friendly calculator."
            << endl
            << "Enter an expression, or an empty line to quit."
            << endl;
    
       for(;;)
       {
          cin.getline(buffer, sizeof buffer);   // Read an input line
          eatspaces(buffer);                    // Remove blanks from input
    
          if(!buffer[0])                      // Empty line ends calculator
             return 0;
    
          cout << "\t= " << expr(buffer)      // Output value of expression
               << endl << endl;
       }
    }
    
    
    // Function to eliminate blanks from a string
    void eatspaces(char* str)
    {
       int i=0;         // 'Copy to' index to string
       int j=0;         // 'Copy from' index to string
    
       while((*(str+i) = *(str+j++)) != '\0')   // Loop while character
                                                // copied is not \0
          if(*(str+i) != ' ')                   // Increment i as long as
             i++;                               // character is not a blank
       return;
    }
    
    
    // Function to evaluate an arithmetic expression
    double expr(char* str)
    {
       double value = 0;          // Store result here
       int index = 0;             // Keeps track of current character position
    
       value = term(str, index);  // Get first term
    
       for(;;)                    // Infinite loop, all exits inside
       {
          switch(*(str+index++))  // Choose action based on current character
          {
             case '\0':                 // We're at the end of the string
                return value;           // so return what we have got
    
             case '+':                         // + found so add in the
                value += term(str, index);     // next term
                break;
    
             case '-':                         // - found so subtract
                value -= term(str, index);     // the next term
                break;
    
             default:                       // If we reach here the string
                cout << endl                // is junk
                     << "Arrrgh!*#!! There's an error"
                     << endl;
                exit(1);
          }
       }
    }
    
    
    // Function to get the value of a term
    double term(char* str, int& index)
    {
       double value = 0;              // Somewhere to accumulate the result
    
       value = number(str, index);    // Get the first number in the term
    
       // Loop as long as we have a good operator
       while((*(str+index)=='*')||(*(str+index)=='/'))
       {
    
          if(*(str+index)=='*')                  // If it's multiply,
             value *= number(str, ++index);      // multiply by next number
    
          if(*(str+index)=='/')                  // If it's divide,
             value /= number(str, ++index);      // divide by next number
       }
       return value;             // We've finished, so return what we've got
    }
    
    
    // Function to recognize an expression in parentheses
    // or a number in a string
    double number(char* str, int& index)
    {
       double value = 0.0;              // Store the resulting value
    
       if(*(str+index) == '(')             // Start of parentheses
       {
          char* psubstr = 0;               // Pointer for substring
          psubstr = extract(str, ++index); // Extract substring in brackets
          value = expr(psubstr);           // Get the value of the substring
          delete[]psubstr;                 // Clean up the free store
          return value;                    // Return substring value
       }
    
       while(isdigit(*(str+index)))     // Loop accumulating leading digits
          value=10*value + (*(str+index++) - 48);
    
                                         // Not a digit when we get to here
       if(*(str+index)!='.')             // so check for decimal point
          return value;                  // and if not, return value
    
       double factor = 1.0;              // Factor for decimal places
       while(isdigit(*(str+(++index))))  // Loop as long as we have digits
       {
          factor *= 0.1;                 // Decrease factor by factor of 10
          value=value + (*(str+index)-48)*factor;   // Add decimal place
       }
    
       return value;                     // On loop exit we are done
    }
    
    
    // Function to extract a substring between parentheses 
    // (requires string)
    char* extract(char* str, int& index)
    {
       char buffer[MAX];         // Temporary space for substring
       char* pstr=0;             // Pointer to new string for return
       int numL = 0;             // Count of left parentheses found
       int bufindex = index;     // Save starting value for index
    
       do
       {
          buffer[index-bufindex] = *(str+index);
          switch(buffer[index-bufindex])
          {
             case ')':
                if(numL==0)
                {
                   buffer[index-bufindex] = '\0';  // Replace ')' with '\0' 
                   ++index;
                   pstr = new char[index-bufindex];
                   if(!pstr)
                   {
                      cout << "Memory allocation failed,"
                           << " program terminated.";
                      exit(1);
                   }
                   strcpy(pstr,buffer);  // Copy substring to new memory
                   return pstr;          // Return substring in new memory
                }
                else
                   numL--;           // Reduce count of '(' to be matched
                break;
    
             case '(':
                numL++;              // Increase count of '(' to be matched
                break;
          }
       } while(*(str+index++) != '\0');// Loop - don't overrun end of string
    
       cout << "Ran off the end of the expression, must be bad input."
            << endl;
       exit(1);
       return pstr;
    }
    hope that helps
    nextus, the samurai warrior

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Honestly I haven't read the entire program yet but good work. It's nice to see young programmers putting so much effort into it. One comment - now try modularizing operations that are common and repetitive, or even just error-prone. Not nitpicking, just an aside...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  2. Library program - need some help
    By Guti14 in forum C Programming
    Replies: 4
    Last Post: 09-08-2004, 12:09 PM
  3. Quick Reply or Normal Reply
    By Thantos in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 05-18-2004, 12:49 PM
  4. People that take AGES to reply!
    By kevinj in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 02-25-2004, 08:35 AM
  5. Quick Reply.
    By Cheeze-It in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 12-07-2002, 02:32 AM