/* File: proj4.c * * This is a sample solution for project 4. There are * many other solutions; some better than this one. * For example, this program makes heavy use of global * variables. I have seen several nice programs that * do not use any global variables. * * Richard Chang, 12/8/94 */ #include #include "genlib.h" #include "simpio.h" #include "strlib.h" /* Global Variables */ string input_line ; int input_length ; int input_pos ; /* Function Prototypes */ void ReadNewLine() ; void SkipBlanks() ; double ReadDouble() ; /* Read in a new line and update position */ void ReadNewLine() { input_line = GetLine() ; input_length = StringLength(input_line) ; input_pos = 0 ; } /* Skip over blank spaces until an interesting character is encountered */ void SkipBlanks() { char c ; while (TRUE) { /* Get non-empty line */ while (input_pos >= input_length) { ReadNewLine() ; } /* Get next character */ c = IthChar(input_line, input_pos) ; /* if non-white space character found, return */ if (!isspace(c)) return ; input_pos++ ; } } /* Read in the next operand and return as a double. */ double ReadDouble() { char c ; int start, stop ; string result ; /* Skip over white space */ SkipBlanks() ; start = input_pos ; /* Look for the end of the number */ while(input_pos < input_length) { c = IthChar(input_line, input_pos) ; if (!isdigit(c) && (c != '.')) break ; input_pos++ ; } /* Extract operand and return as double */ stop = input_pos - 1 ; result = SubString(input_line, start, stop) ; return( StringToReal(result) ) ; } main() { char operator ; double operand, result ; printf("Enter an expression ending with '='\n") ; /* Initialize Global variables */ ReadNewLine() ; /* Get first operand */ result = ReadDouble() ; while(TRUE) { /* Get the operator */ SkipBlanks() ; operator = IthChar(input_line, input_pos) ; input_pos++ ; /* End of expression??? */ if (operator == '=') { printf("Answer = %g\n", result) ; break ; } /* Process operator */ switch(operator) { case '+' : operand = ReadDouble() ; result = result + operand ; break ; case '-' : operand = ReadDouble() ; result = result - operand ; break ; case '*' : operand = ReadDouble() ; result = result * operand ; break ; case '/' : operand = ReadDouble() ; result = result / operand ; break ; default : Error("Unknown operator: %c", operator) ; } } }