A Good Example Of A Loop in C++
//this is a good example of a C++ loop
//the while loop was used because there need to be breaks within the loop
//in this case a for loop would not be appropriate
#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;
int valid = 1;
stack_t result = 0.0;
//here a while loop is preferred to a for loop
while ((valid) && (counter < strlen(input_array)))
{
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)
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;
}
default:
valid = 0;
}
}
}
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: Friday, 21-Aug-2020 15:28:16 CST.
Copyright: Department of Computer Science, University of Regina of Regina.
[CS Department]