logoISU  

CS 456 - Systems Programming

Spring 2024

Displaying ./code/apr17/rpnFunctions.c

#include "rpn.h"

static int sp = 0;              // stack pointer 
static double values[MAXSIZE];  // stack


//stack functions
double push(double number) {
  if ( sp < MAXSIZE )       // if we still have room in the stack, add number, then increment pointer
    values[sp++] = number;
  else
    printf("Error: push on full stack.\n");  // stack is full
  return number;
}

double pop() {
  if ( sp > 0 )  //if there is still stuff on the stack
    return values[--sp]; // decrease stack pointer return that value
  else {
    printf("Error: pop from empty stack.\n"); //the stack was empty
    clear_stack();
    return 0;
  }
}

void clear_stack() {
  sp = 0; //sets the stack pointer to zero
}

// operator functions
int getop(char *dest, int limit){
  int i, c;



  // we get a character from the user/input stream then run a couple checks on it
  while ( (c = getchar()) == ' ' || c == '\t' || c == '\n' ) //filters out whitespace, tab and newline characters
    ; 
  

  if ( c != '.' && (c < '0' || c > '9') ) //do we have a non-numerical character (that's also not a decimal point)
    return c; // if so, return that character
  

  // if we get down here , then we must have a number (or decimal point)
  dest[0] = c;  //put that character in first entry of the dest buffer

  //checking user input for numerical characters
  for(i = 1; (c = getchar()) >= '0' && c <= '9'; ++i) 
    if ( i < limit )
      dest[i] = c;

  if ( c == '.' ) { // collect fractional portion
    if ( i < limit )
      dest[i] = c;
    for(i++; (c = getchar()) >= '0' && c <= '9'; ++i)
      if ( i < limit )
        dest[i] = c;
  }
  if ( i < limit ) { /* number is ok */
    ungetc(c, stdin);
    dest[i] = '\0';
    return NUMBER;
  } else { /* input is too big; skip rest of line */
    while ( c != '\n' && c != EOF )
      c = getchar();
    dest[limit - 1] = '\0';
    return TOOBIG;
  }
}