A Bad Example Of A Loop in C++

//this is a bad example of a C++ loop
//This is the same program as the good example of the C++ loop.
//However, in this program a for loop was used instead of a while
//which isn't appropriate for this sort of loop.
//It also is inappropriate because we use break within the loop which
//could result in problems.

#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "StackLi.h"  //includes stack class          

typedef float stack_t;
#define MAX_SIZE_INPUT_ARRAY 80
#define MAX_SIZE_NUM_ARRAY 80

int main (void)
    {
    //here we are using a stack template of float type
    Stack StackObj;
    char input_array[MAX_SIZE_INPUT_ARRAY];
    char tmp_array[MAX_SIZE_NUM_ARRAY];
    
    cout << "Enter a postfix string each integer followed by a ,\n";
    cin >> input_array;

    //holds the position in the array
    int counter = 0;
    int tmp_num = 0;
 
    stack_t result = 0.0; 
 
    int j = 0;
    //here we cram a for loop into what should have been while loop
    for(j = 0; j <= strlen(input_array); j++)
	{
	if (isdigit(input_array[counter]))
		{
      		tmp_array[tmp_num] = input_array[counter]; 
                tmp_num = tmp_num + 1;
		counter = counter + 1;
		}
	else
		{
                stack_t RightHandSide = 0.0;
		stack_t LeftHandSide = 0.0;
                
		switch (input_array[counter])
	            {
		    case ',':
			{	
			counter = counter + 1;
			if (tmp_num==0)
			    break;
			else
			    {
			    result = atoi(tmp_array);
		            StackObj.push(result);
                            int i = 0;
			    for (i = 0 ; i <= tmp_num ; i++)
			        {
				tmp_array[tmp_num] = '\0';
 				}			    
  			    tmp_num = 0;
			    break;
			    }
		        }
		    case '+':
			{
			RightHandSide = StackObj.topAndPop();
			LeftHandSide = StackObj.topAndPop();
			result = LeftHandSide + RightHandSide;
			StackObj.push(result);
			counter = counter + 1;
			break;
			}
		    case '-':
			{
			RightHandSide = StackObj.topAndPop();
			LeftHandSide = StackObj.topAndPop();
			result = LeftHandSide - RightHandSide;
			StackObj.push(result);
			counter = counter + 1;
			break;
			}
		    case '*':
			{
			RightHandSide = StackObj.topAndPop();
			RightHandSide = StackObj.topAndPop();
			result = LeftHandSide * RightHandSide;
			StackObj.push(result);
			counter = counter + 1;
			break;
			}
		     case '/':
			{
			RightHandSide = StackObj.topAndPop();
			LeftHandSide = StackObj.topAndPop();
			result = LeftHandSide / RightHandSide;
			StackObj.push(result);
			counter = counter + 1;
			break;
			}
		     }
		}
	}
	result = StackObj.topAndPop();
	cout << result << endl;
	if(StackObj.isEmpty() == 0)
		cout << "Not enough operators.\n";
	return 0;
}





This page was modified by Tanya Douglas at: Sunday, 25-Mar-2012 18:14:36 CST.
Copyright: Department of Computer Science, University of Regina of Regina.


[CS Department]