BabaSvoloch
BabaSvoloch

Reputation: 311

Comparing contents of char array at specific index to char literal - cpp

I have a really simple question here, just not sure what to use to solve it.

I'm trying to write a program in c++ that uses an explicit stack to check whether the contents of a character array contains parentheses that are balanced.

I haven't implemented the stack yet. My question is how to go through the character array and compare the contents at each index position to char literals.

Basically the logic of the problem is that you traverse the char array one pos at a time, and every time you get an opening paren, you push that char onto the stack, and every time you get a closing paren, you compare it to the char on top of the stack, and if they're the same, you pop the stack and continue traversing the char array. If you get a closing paren, and either the stack is empty, or the char on top doesn't match the closing paren (i.e. curly brace instead of square bracket), the char array is not balanced.

So I have a for loop to traverse the char array, and the first thing I need to do is write an if statement, which basically says: if the element at position 'i' in the array is "(" or if it's "{" or if it's "[", push it onto the stack.

But I don't know how to compare the contents of a certain index position to a char literal.

Here's what I tried to do:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;

int main(){
    stack<char> S;
    char* parens = "{()()}";
    int len = strlen(parens);

    for(int i = 0; i < len; i++){
        if(parens[i] == "(" || parens[i] == "{" || parens[i] == "["){
            S.push(parens[i]);
        } else { // etc

Visual studio didn't like that if statement. It says it can't compare "char" with "const char *."

I also tried using strcmp(parens[i], "(/{/[") == 0 , and it didn't like that either. I have to use a character array instead of a string since I need to traverse it using an index pos, but I'm not sure how to compare these.

I would really appreciate any help, thank you

Upvotes: 2

Views: 2600

Answers (1)

RichS
RichS

Reputation: 550

Your if statement compares to string literals. String literals are all in double quotes like these: "{", "(", and "[". Char literals are all in single quotes like these: '{', '(', and '['.

Try this code sample. Instead of comparing a literal string to a char, it compares a literal char to a char. I also added const in front of your string literal declarations because some C++ compilers insist such variables be const char * instead of just char *.

int main(){
    stack<char> S;
    const char* parens = "{()()}";
    const int len = strlen(parens);

    for(int i = 0; i < len; i++){
        if ( ( parens[i] == '(' ) || ( parens[i] == '{' ) || ( parens[i] == '[' ) {
            S.push(parens[i]);
        } else { // etc

Upvotes: 1

Related Questions