无论用户输入如何C++程序都会返回"valid"结果



这个程序应该检查括号是否平衡(打开和关闭(。程序运行,但对于所有用户输入返回valid

#ifndef _STACKLSAB_H_
#define _STACKSLAB_H_
#include <stack>
#include <string>
#include <vector>
#include "namevaluepair.h"
using namespace std;
class Stacks
{
public:
bool balanced(string exp);
bool match(char open, char closed);

private:
string st_PostData;
};
#endif

stacksLab.cpp(我的程序在repl.it中工作,但不使用cgi(:

#include <iostream>
#include <sstream>
#include "stacksLab.h"
#include <stack>
using namespace std;
bool Stacks::match(char open,char closed)
{
if(open == '(' && closed == ')') return true;
else if(open == '{' && closed == '}') return true;
else if(open == '[' && closed == ']') return true;
return false;
}
bool Stacks::balanced(string exp)
{
stack<char>  S;
for(int i = 0;i<exp.length();i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if(S.empty() || !match(S.top(),exp[i]))
return false;
else
S.pop();
}
}
return S.empty();
}

main.cpp

#include <iostream>
#include "stacksLab.h"
#include <stack>
using namespace std;
int main()
{
/// complete the http header
cout << "Content-type: text/htmlnn";
Stacks st;
string expression;
cin>>expression;
if(st.balanced(expression))
cout<<"Validn";
else
cout<<"Not Validn";
}

我认为这就是我的程序不会正确返回但不确定该走哪条路的原因。

<form action="runme.cgi" method="POST">
<table align="center" bgcolor="antiquewhite">
<tr>
<td align="right">Enter parentheses here:</td>
<td><input type="text" name="parentheses "/> </td>
</tr>
<tr>
<td align="right"><input type="submit" /></td>
</tr>
</table>
</form>

问题不在于堆栈处理(我给你的代码做了一些基本的测试,它似乎可以工作(,而在于你接受输入的方式。

cin << expression;行将读取输入中的字符,直到但不包括第一个空格(即换行符空格字符(。因此,如果您输入字符串abc (((}}}(很明显,它有不平衡的括号(,那么您的程序将显示valid,因为它正在测试的字符串只是abc部分。

要解决此问题,请使用std::getline函数,该函数读取给定分隔符(默认情况下为换行符(的第一个

根据我运行的(诚然,是有限的(测试判断,以下main在代码其余部分不变的情况下工作:

int main()
{
cout << "Content-type: text/htmlnn";
Stacks st;
string expression;
getline(cin, expression, 'n'); // The 'n' argument can be omitted, as this is the default
if (st.balanced(expression))
cout << "Validn";
else
cout << "Not Validn";
return 0;
}

作为额外的"建议改进",您可能应该将balanced函数中的int i循环索引更改为size_t类型,这实际上是标准库容器对象(如std::stringstd::vector(的[]运算符的操作数所需的类型:

bool Stacks::balanced(string exp)
{
stack<char>  S;
for (size_t i = 0; i < exp.length(); i++) { // size_t is more precise than int
//... and so forth

最新更新