【发布时间】: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++