分隔符匹配简单程序不起作用

Delimiter matching simple program won't work

本文关键字:程序 不起作用 简单 分隔符      更新时间:2023-10-16

我已经看了好几个小时了。这个程序会编译,只是不能正确检测错误。由于某种原因,当我输入hey[)或hey{]等时,它会起作用。但它不适用于hey[]或hey{]。显然,在所有情况下,它都应该检测到错误,但由于某种原因"hey"后面的空格会产生影响。

#include<iostream>
#include <stack>
using namespace std;
bool delimiterMatching(char *file){
  stack<char> x;
  int count = 0;
  char ch, onTop, check;
  while(ch != ''){
    ch = file[count];
    if (ch == '(' || ch == '[' || ch == '{')
      x.push(ch);
    else if (ch == ')' || ch ==  ']' || ch == '}') {
      onTop == x.top();
       x.pop();
      if((ch==')' && onTop!='(') || (ch==']' && onTop!='[') || (ch=='}' && 
                                onTop!= '{'))
    return false;
    }
  count++;
  }
  if (x.empty())
    return true;
  else 
    return false;
}

int main()
{
  char *test = new char();
  cout << "enter sentence: ";
  cin >> test;
  if (delimiterMatching(test))
    cout << "success" << endl;
  else 
    cout << "error" << endl;
  return 1;
}

使用cin >> test,在cin遇到空格之前,您不会得到一个完整的句子,而只能得到一个字符串。因此,如果键入(hey ),则t将为(hey,并且右大括号将仅由下一个>>读取,而(hey)将按预期工作。

您的test分配存在第二个问题,可能太短,无法进行合理的输入。

将main()更改如下:

char *test = new char[256];   // enough space.  COnsider also string  
cout << "enter sentence: ";
cin.getline(test, 256);       // full line input. 
...

delimiterMatching()中还有两个讨厌的bug。

  • 首先,在while条件中使用未初始化的ch。将ch初始化为非空字符,或者使用while (file[count])
  • 你注意到onTop == x.top();了吗?不应该是onTop = x.top();