Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/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++ - Fatal编程技术网

C++中的分隔符匹配——分段错误(内核转储)

C++中的分隔符匹配——分段错误(内核转储),c++,C++,我在运行程序时不断遇到分段错误。我不知道出了什么事。我用谷歌搜索了错误信息,我只是不知道它是什么意思。任何帮助都会很好 #include<iostream> #include <stack> using namespace std; bool delimiterMatching(char *file){ stack<char> x; int count = 0; char ch, onTop, check; while(ch != '/n')

我在运行程序时不断遇到分段错误。我不知道出了什么事。我用谷歌搜索了错误信息,我只是不知道它是什么意思。任何帮助都会很好

#include<iostream>
#include <stack>
using namespace std;

bool delimiterMatching(char *file){
  stack<char> x;
  int count = 0;
  char ch, onTop, check;
  while(ch != '/n'){
    ch = file[count];
    if (ch == '(' || '[' || '{')
      x.push(ch);

    else if (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[50];
  cout << "enter sentence: ";
  cin >> test;

    if (delimiterMatching(test))
    cout << "success" << endl;
  else 
    cout << "error" << endl;

  return 1;
}

你不能用这样的比较

    if (ch == '(' || '[' || '{')
试一试


分段错误表示程序试图访问无效的内存地址。通常,这意味着您取消了对悬空指针的引用,或者索引到了数组的末尾

在这种情况下,问题似乎是您的whilech!='/n'线。它有两个问题:

首先,“/n”不是有效的字符文字。您的意思可能是“\n”,它表示换行符。 其次,字符串不会以换行符结尾,因为cin>>测试读取一行,并在结尾处丢弃换行符。您的循环将经过数组的结尾,进入内存中其后的任何位置,试图找到换行符,最终它将到达无法访问的位置,从而导致分段错误。您应该检查“\0”,它是实际标记字符串结尾的空字符。 当我换衣服的时候/到中国去\0',程序不会崩溃


顺便说一句,使用std::string比使用char[50]更容易、更安全。

您的意思是\n而不是/n?另外,请查看第一个if-else块中的条件。它们看起来非常错误。使用所有警告和调试信息编译g++-Wall-g。然后使用调试器gdbif ch==a | | b并不意味着ch等于a或b,而是意味着ch等于a或b不是0。如何使用std::string?当我这样做时,它说不能从字符串转换为字符*。很抱歉问了这么多基本的问题。
    if (ch == '('  || ch== '[' || ch=='{')