I'm assuming that the input will have each element separated by whitespace,
such as "
5 6 + 3 * p" or "
355000 113 / p". If that is the case, then you don't necessarily have to do a lot of low-level validation of numbers.
Something like this should work (well, I started testing this, but there may be a few bugs to be ironed out).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
int main()
{
node * stack = new node;
string user_input;
cout << "Enter an input \n";
int s1;
int s2;
while (cin >> user_input)
{
if (isdigit(user_input[0]) || user_input.size() > 1)
{
int num;
string dummy;
istringstream numss(user_input);
if ((numss >> num) && !(numss >> dummy))
{
push(num, stack);
}
}
else if (user_input == "+") // Add
{
s1 = pop(stack);
s2 = pop(stack);
push(s1 + s2, stack);
}
Etc. etc. ...
|
At line 13, the assumption is made that if either the first character is numeric, or the string contains more than one character, it must be a number. (I've not handled the case where there is invalid input).
Line 17, make a
stringstream
from the input. Attempt to extract first an integer (should succeed) followed by any other characters (should fail). If that works, push the number onto the stack.
Other comments. I've used local rather than global variables. It's generally a good idea to restrict the scope of variables to just the place where they are used.
wh33lybrdy wrote: |
---|
Previously I was using three files: main.cpp stack.cpp and stack.h |
Yes, that sounds a reasonable idea. But if the other files are very small, there may not be any real motive for doing so.