Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 分隔符匹配简单程序赢得';行不通_C++_Stream_Delimiter - Fatal编程技术网

C++ 分隔符匹配简单程序赢得';行不通

C++ 分隔符匹配简单程序赢得';行不通,c++,stream,delimiter,C++,Stream,Delimiter,我已经看了好几个小时了。这个程序会编译,只是不能正确地检测错误。出于某种原因,当我输入hey[)或hey{]等时,它会起作用。但它对hey[)或hey{]不起作用。显然,在所有情况下,它都应该检测到错误,但出于某种原因,“hey”后面的空格会起作用 #include<iostream> #include <stack> using namespace std; bool delimiterMatching(char *file){ stack<char>

我已经看了好几个小时了。这个程序会编译,只是不能正确地检测错误。出于某种原因,当我输入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 != '\0'){
    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;
}
#包括
#包括
使用名称空间std;
布尔定界符(字符*文件){
堆栈x;
整数计数=0;
char ch、onTop、check;
而(ch!='\0'){
ch=文件[计数];
如果(ch='('| | ch='['| | ch=='{')
x、 推(ch);
else如果(ch=')'| | ch=']'| | ch='}'){
onTop==x.top();
x、 pop();
如果((ch=')和&onTop!=')(')| |(ch=']')和&onTop!='['))| |(ch='}')和
onTop!='{'))
返回false;
}
计数++;
}
if(x.empty())
返回true;
其他的
返回false;
}
int main()
{
char*test=new char();
cout>检验;
如果(测试)

使用
cin>>测试,你不会得到一个完整的句子,只有一个字符串,直到cin遇到空白。因此,如果你键入
(嘿)
,测试将是
(嘿)
,右括号将只在下一个
>
读取,而
(嘿)
将按预期工作

您的
测试
分配还有第二个问题,可能太短,无法进行合理的输入

将main()更改如下:

char *test = new char[256];   // enough space.  COnsider also string  
cout << "enter sentence: ";
cin.getline(test, 256);       // full line input. 
...
<代码> char * test =新char(256);//足够的空间。
非常感谢!看起来修复onTop=xtop()修复了很多。感谢您对空格的解释!另外,您如何将测试初始化为字符串变量?因为我无法将字符串传递到char*函数中。对于这些愚蠢的问题,我很抱歉。最后,我不明白为什么(file[count])不会进入无限循环,因为计数总是递增的。因为
while(file[count])
的意思与
while(file[count]!='\0')
的意思相同。对于字符串主题,由于delilimerMatching只读,您可以将其参数定义为
const char*
,因此如果测试是字符串,您可以通过
test.c_str()
作为参数