2016-09-23 100 views
1

我试图编写一个代码来检查输入字符串中的括号对,并输出“成功”(对于匹配对的输入)或第一个不匹配的右括号的从1开始的索引。当我编译错误:'。'之前的预期主要表达式。令牌

expected primary expression before '.' 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; 
} 
+4

'Bracket.Matchc(next)' - 括号是*类型*。你需要一个*对象*来工作。 – WhozCraig

回答

1

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

解决方案 -

要创建一个对象,你需要在程序中包含下面的代码。

即..

在你main,包括以下语句来创建支架的对象。

Bracket brackObj(next, 0); 

现在,包括在stack

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

此特定对象而现在,你可以叫你在同一对象上的方法Matchc

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

是的,我忘了为Bracket类创建一个对象。非常感谢您的帮助! :) – Kishaan92

相关问题