这个程序基本上只是考虑括号,括号和大括号来检查是否正确构造了一个语句(数学)。它使用堆栈来比较最近读取的分隔符,以查看该分隔符的结束类型是否存在,否则它表示它没有正确构造。我卡住了,因为它总是返回声明不正确。这就是我到目前为止所做的:
#include <iostream>
#include <stack>
using namespace std;
bool delimiterMatching(char* file);
void main(){
char fileName[50];
cout << "Enter a statement (Ex. s=t[5]+u/(v*(w+y)); : ";
cin >> fileName;
cout << endl;
if(delimiterMatching(fileName))
cout << endl << "Your statement was constructed successfully." << endl;
else cout << endl << "Your statement is incorrectly constructed." << endl;
}
bool delimiterMatching(char* file){
stack<char> var;
int counter = 0;
char ch, temp, popd;
do{
ch = file[counter];
if(ch == '(' || ch == '[' || ch == '{')
var.push(ch);
else if(ch == '/'){
temp = file[counter+1];
if(temp == '*')
var.push(ch);
else{
ch = temp;
continue;
}
}
else if(ch == ')' || ch == ']' || ch == '}'){
popd = var.top();
var.pop();
if(ch != popd)
return false;
}
else if(ch == '*'){
temp = file[counter+1];
popd = var.top();
var.pop();
if(temp == '/' && popd != '/')
return false;
else{
ch = temp;
var.push(popd);
continue;
}
}
counter++;
}while(ch != '\n');
if(var.empty())
return true;
else return false;
}
我已经尝试使用谷歌搜索一些提示,但没有任何帮助。我调试了它,如果我使用“s = t [5] + u /(v *(w + y));”,当它读取5之后的第二个括号时,它显然不是同一个字符。那么如何比较开头符号和结束符号?
我感谢任何帮助。如果我自己弄清楚的话,我会编辑/评论它。谢谢你的时间!
我知道这是最终的代码:
#include <iostream>
#include <stack>
using namespace std;
bool delimiterMatching(char* file);
void main(){
char fileName[50];
cout << "Enter a statement (Ex. s=t[5]+u/(v*(w+y)); : ";
cin >> fileName;
cout << endl;
if(delimiterMatching(fileName))
cout << endl << "Your statement was constructed successfully." << endl;
else cout << endl << "Your statement is incorrectly constructed." << endl;
}
bool delimiterMatching(char* file){
stack<char> var;
int counter = 0;
char ch, temp, popd;
do{
ch = file[counter];
if(ch == ';')
break;
if(ch == '(' || ch == '[' || ch == '{')
var.push(ch);
else if(ch == '/'){
temp = file[counter+1];
if(temp == '*')
var.push(ch);
else{
counter++;
continue;
}
}
else if(ch == ')' || ch == ']' || ch == '}'){
popd = var.top();
var.pop();
if((ch==')' && popd!='(') || (ch==']' && popd!='[') || (ch=='}' && popd!='{'))
return false;
}
else if(ch == '*'){
temp = file[counter+1];
popd = var.top();
var.pop();
if(temp == '/' && popd != '/')
return false;
else{
counter++;
var.push(popd);
continue;
}
}
counter++;
}while(ch != '\n');
if(var.empty())
return true;
else return false;
}
答案 0 :(得分:3)
检查结束括号(例如')',']'或'}')是否与从堆栈弹出的值匹配。它们永远不会是平等的,因为你只是推动括号的左侧('(','['或'{'),同时将它与括号的右侧进行比较。
看起来应该是这样的:
else if(ch == ')' || ch == ']' || ch == '}'){
popd = var.top();
var.pop();
if((ch==')' && popd!='(') || (ch==']' && popd!='[') || (ch=='}' && popd!='{'))
return false;
}