Reputation: 75
I've googled and searched my problems and maybe I'm not using the correct search terms because I'm not finding any solutions to my problem.
What I'm trying to do is do a postfix calculator expression using the push and pop methods and templates.
Per my professor's words
Input
The input is a string that represents a postfix expression. To simplify the problem, your calculator will be restricted to operating on single-digit non-negative integers. Only the following characters are allowed in the string:
the operators '+', '-'. '*', and '/' the digits '0' through '9' the space (blank) character ' '
Example input: 2 4 3 * +
Result: 14
To handle spaces in the input, you will need to make one minor addition to the algorithm on page 204 of your textbook:
if (ch is a blank)
ignore it end if
The program is separated into 3 files, the main file, the template, and the virtual template. He wants as little as possible in the main file, most of the checking and calculating done in the template.
#include <iostream>
#include <string>
#include "ArrayStack.h"
using namespace std;
int main()
{
ArrayStack<string> stack;
string items;
bool done = false;
char decision;
while(!done) // check to see if the user wants to do more calculations
{
cout << "Enter postfix expression: ";
getline(cin, items);
for(int x = 0;x < items.length();x++)
{
stack.push(&items[x]);
cout << "Pushing " << &items[x] << endl;
}
cout << "Done? Y/N: ";
cin >> decision;
if((decision == 'y') || (decision == 'Y')) done = true;
}
}
and here's the relative function of the template
template<class ItemType>
bool ArrayStack<ItemType>::push(const ItemType& newEntry)
{
bool result = false;
if (top < MAX_STACK - 1) // Does stack have room for newEntry?
{
//////////////////////////////////////
if(isdigit(&newEntry))
{
top++;
items[top] = newEntry;
result = true;
}
//////////////////////////////////////
} // end if
return result;
} // end push
My problem is that isdigit can't do anything when it's a constant char, but I'm not allowed to check to see if it's a digit, space or /-+* in the main file. I'm not sure how to proceed. Am I using the wrong function, or am I just not using it properly?
Upvotes: 0
Views: 521
Reputation: 12174
you might want to change the type to unsigned char
instead.
ArrayStack<unsigned char> stack;
For the isdigit()
works with unsigned char
.
Also, push unsigned char
items in your loop and not a pointer
:
stack.push(items[x]); // don't pass a pointer
UPDATE
As per isdigit()
in cppreference:
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
which is different in cplusplus.com. So take note.
Thus, your ItemType
should be unsigned char
Upvotes: 2