0
#include "cstack.h"
#include <iostream>
#include <cstring>
using namespace std;

bool isValidExpression (CStack&, char*);

int main (void)
{
    char expression[21];
    expression[0-21]=0;
    cout<< "Enter an expression: ";
    cin >>expression;
    CStack stack1;

    if (isValidExpression (stack1, expression)==true)
    {
        cout << "\nIt's a valid expression";
    }
    else
    {
        cout << "\nIt's NOT a valid expression";
    }
    return 0;
}

bool isValidExpression (CStack& stackA, char* strExp)
{
    for(int a=0;a<21 && strExp[a]!=0;a++)
    {
        if(strExp[a]="}"||"]"||")") //This is the issue right here
        {
            cout<<"Action A" <<endl;
        }
        else
        {
            stackA.push(strExp[a]);
        }
    }
    return true;
}

The problem I am having is that whatever input I put in, Action A always occurs. If I input [ for example, I still get action a which is not the desired result. I have always used strings for things like this, but we are required to use cstring in this program. How would you edit this to make it work?

WhozCraig
  • 65,258
  • 11
  • 75
  • 141

2 Answers2

3

Try to update:

if(strExp[a]="}"||"]"||")")

to:

if(strExp[a]=='}'|| strExp[a]==']'|| strExp[a]==')' )
billz
  • 44,644
  • 9
  • 83
  • 100
3

if(strExp[a]="}"||"]"||")") will always be true because this uses "]" and ")" as the booleans to the || operators, and the string constants themselves resolve to non-zero const char *s which are considered true. Additionally, the single = is assignment, not comparison, this means all three parts of the if condition are true

The above condition reads as:

if (the lower 8 bits of the pointer generated for"}"[true]
or the pointer generated for "]" is nonzero [true]
or the pointer generated for ")" is nonzero [true])

what I think you mean to do is

if(strExp[a]=='}' || strExp[a]==']' || strExp[a]==')')

also note that the double quotes are replaced with single quotes here. Use single quotes when examining a single character rather than double quotes. Also use == for comparison.

If you're compiling with g++ you should enable warnings with g++ -Wall -Wextra, any sane compiler would have generated warnings on that line for all the reasons stated.

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174