我正在写一个简单的括号检查器。应该很容易。当它全部在一个功能中时,我让它工作,但我还需要为标准输入做一些事情。所以我认为最好做2个功能。话虽如此,我在第 82 行检查堆栈是否为空时遇到错误。无论出于何种原因,它都不允许我检查堆栈的顶部是否为空。我尝试在测试程序中查看它是否是某种引用错误,或者是否通过进入其他方法超出范围。它不是。应该可以正常工作,因为它是一个全局变量。
关于我做错了什么的想法?我所有的互联网和知识都指向我做正确的想法。
以下是所有代码。它是可编译的。如果我需要澄清任何事情,我会非常乐意。
谢谢
#include <iostream>
#include <sstream>
#include <stack>
#include <deque>
#include <fstream>
#include <cstdlib>
using namespace std;
stack<char> BracketsCheck;
int linecounter = 0;
int FileNumber = 1;
int pos;
string str ="";
string filename;
int validate(string string)
{
int size = str.size();
for (int i = 0; i < str.size(); i++)
{
pos = i;
if ((str[i] == '(' ) || (str[i] == '[') || (str[i] == '{'))
{
BracketsCheck.push(str[i]);
}
else if (str[i] == ')')
{
if (BracketsCheck.top() == '(')
BracketsCheck.pop();
else
{
cout << filename << ":" << linecounter << ":" << pos << "ERROR: missing open parenthesis" << endl;
return EXIT_FAILURE;
}
}
else if (str[i] == ']')
{
if (BracketsCheck.top() == '[')
BracketsCheck.pop();
else
{
cout << filename << ":" << linecounter << ":" << pos << "ERROR: missing open squre bracket" << endl;
return EXIT_FAILURE;
}
}
else if (str[i] == '}')
{
if (BracketsCheck.top() == '{')
BracketsCheck.pop();
else
{
cout << filename << ":" << linecounter << ":" << pos << "ERROR: missing open curly brace" << endl;
return EXIT_FAILURE;
}
}
}
}
int main(int argc, char* argv[])
{
// BracketsCheck.top() = 'h';
if (argc == 1)
{
cin >> str;
cout << "no arguments" << endl;
validate (str);
return 0;
}
else
{
while (argv[FileNumber] != NULL)
{
filename = argv[FileNumber];
ifstream inFile(argv[FileNumber]);
cout << argv[FileNumber]<<endl;
while (getline(inFile, str))
{
validate(str);
linecounter++;
}
if (BracketsCheck.top() != NULL)
{
cout << "got to null checker" << endl;
cout << filename << ":" << linecounter << ":" << pos << "umatched closing brace" << endl;
return EXIT_FAILURE;
}
FileNumber++;
}
return 0;
}
}