错误:令牌之前'.'预期的主表达式

Error: expected primary expression before '.' token

本文关键字:表达式 令牌 错误      更新时间:2023-10-16

我试图编写代码来检查输入字符串中的括号对,并打印出"成功"(对于具有匹配对的输入)或第一个不匹配的结束括号的基于1的索引。

但是我得到一个错误:

期望在'之前的主表达式。' token

,当我编译。

#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;
}

Reason -您直接使用类Bracket而不是对象。

方案-

要创建一个对象,需要在程序中包含以下代码:

即. .

在您的main中,包含以下语句来创建一个括号对象。

Bracket brackObj(next, 0);

现在,将这个特定对象包含在stack

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

现在,您可以在同一个对象上调用您的方法Matchc

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