【发布时间】:2013-11-30 21:19:06
【问题描述】:
这个程序基本上只是检查一个语句(数学)是否在考虑括号、圆括号和花括号的情况下正确构造。它使用堆栈来比较最近读取的分隔符,以查看该分隔符的结束类型是否存在,否则它表示它没有正确构造。我被卡住了,因为它总是返回该语句不正确。这是我目前所拥有的:
#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;
}
【问题讨论】:
-
你能用C++11 regex吗?见示例代码here
标签: c++ visual-c++ stack