Kishaan92 Kishaan92 - 2 months ago 25
C++ Question

Error: expected primary expression before '.' token

I'm trying to write a code to check the bracket pairs in an input string and print out either "Success" (for an input with matched pair) or the the 1-based index of the first unmatched closing bracket.

However I'm getting an error:


expected primary expression before '.' token


when I compile.

#include <iostream>
#include <stack>
#include <string>

struct Bracket {
Bracket(char type, int position):
type(type),
position(position)
{}

bool Matchc(char c) {
if (type == '[' && c == ']')
return true;
if (type == '{' && c == '}')
return true;
if (type == '(' && c == ')')
return true;
return false;

}

char type;
int position;
};


int main() {
std::string text;
getline(std::cin, text);
int z;

std::stack <Bracket> opening_brackets_stack;
for (int position = 0; position < text.length(); ++position) {
char next = text[position];

if (next == '(' || next == '[' || next == '{') {
opening_brackets_stack.push(Bracket(next,0));
}

if (next == ')' || next == ']' || next == '}') {

if(Bracket.Matchc(next) == false || opening_brackets_stack.empty() == false)
{
z = position;
}

else
{
opening_brackets_stack.pop();
}

}
}

if (opening_brackets_stack.empty())
{
std::cout << "Success";
}

else
{
std::cout << z;
}
return 0;
}

Answer

Reason - You are directly using the class Bracket instead of an object.

Solution -

To create an object, you need to include the following code in your program.

i.e..

In your main, include the following statement to create an object of Bracket.

Bracket brackObj(next, 0);

Now, include this particular object in the stack

if (next == '(' || next == '[' || next == '{') {
    opening_brackets_stack.push(brackObj);
}

And now, you can call your method Matchc on the same object.

if(brackObj.Matchc(next) == false ......