【问题标题】:Error: expected primary expression before '.' token错误:“。”之前的预期主表达式令牌
【发布时间】:2017-02-01 17:59:23
【问题描述】:

我正在尝试编写代码来检查输入字符串中的括号对并打印出“成功”(对于具有匹配对的输入)或第一个不匹配的右括号的从 1 开始的索引。

但是我遇到了一个错误:

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

当我编译时。

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

【问题讨论】:

  • Bracket.Matchc(next) - 括号是 type。你需要一个 object 来让它工作。

标签: c++


【解决方案1】:

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

解决方案-

要创建对象,您需要在程序中包含以下代码。

即..

在您的main 中,包含以下语句以创建Bracket 对象。

Bracket brackObj(next, 0);

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

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

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

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

【讨论】:

  • 是的,我忘了为 Bracket 类创建一个对象。非常感谢您帮助我! :)
猜你喜欢
  • 2013-12-23
  • 1970-01-01
  • 2012-10-30
  • 2013-06-08
  • 2020-10-30
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多