2016-09-23 96 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

相關問題