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