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;
}
'Bracket.Matchc(next)' - 括號是*類型*。你需要一個*對象*來工作。 – WhozCraig