strcmp can't convert char* to const char* in a prefix evaluation code (c++)

168 views Asked by At

I'm writing a code to evaluate a prefix expression. The values of the expression are separated by spaces. So if the input is "+ * 87 89 666", I should get 8409 as the answer. The concept of my code is to store the values to an array and then evaluate them value by value. Right now I'm stuck at the switch part because the compiler says invalid conversion from char to const char*

#include <iostream>
#include <bits/stdc++.h>
#include <algorithm>
#include <stack>
#include <string>
#include <sstream>

using namespace std;

char n[99999][6]={};

int evaluatePrefix(int l)
{
    stack<int> Stack;

    for (int j = l; j >= 0; j--) {
        string x=n[j];
        if (n[j][0]!='+' || n[j][0]!='-' || n[j][0]!='*' || n[j][0]!='/'){
            stringstream ss;
            int a;
            ss<<x;
            ss>>a;
            Stack.push(a);
        }
        else {
            int o1 = Stack.top();
            Stack.pop();
            int o2 = Stack.top();
            Stack.pop();
            if (strcmp(n[j], '+')==0){
                Stack.push(o1 + o2);
            }
            else if (strcmp(x, '-')==0){
                Stack.push(o1 - o2);
            }
            else if (strcmp(x, '*')==0){
                Stack.push(o1 * o2);
            }
            else if (strcmp(x, '/')==0){
                Stack.push(o1 / o2);
            }
        }
    }

    return Stack.top();
}

int main()
{
    char e[99999], w[99999];
    int i=0;
    scanf("%[^\n]%*c",e);
    char *token = strtok(e, " ");
    while (token != NULL)
    {
        strcpy(n[i], token);
        token = strtok(NULL, " ");
    }
    return 0;
}
1

There are 1 answers

1
Jeffrey On

You wrote:

if (strcmp(n[j], '+')==0)

n[j] decays into a char*, but '+' is a single char, not a char*. strcmp needs two char pointers.

https://en.cppreference.com/w/c/string/byte/strcmp

So, you should use:

if (strcmp(n[j], "+")==0)