程序没有进入如果条件,给出分段错误

program doesnt enter if condition , gives segmentation fault

本文关键字:分段 错误 条件 如果 程序      更新时间:2023-10-16

代码有点像

cin >> n  // test cases
for( n times )
{ 
 .....
  for(;;)
    {
     getline(cin,inp) //inp is supposed to be +,-,*,,0-9,if simply enter pressed program passes out of loop
      for(;;)
      {
       if (inp[0] == '*')
       {
        do stuff...
       }
       if (inp[0] == '')
       {
        do stuff...
       }         
       if (inp[0] == '+') \ this is where the problem occurs
       {
        do stuff...
       } 
    .....
    .....
        }
    }
return 0 ;
}

这是带有一些注释的实际代码,我已经尝试在程序中将中缀转换为后缀。这是我的意见和问题。。。

>1          //1 test case

>3           //if condition as it should entered line 124
>inp[0] 3   //confirms 3 is inp[0]
>*          //works as it should (if condn entered line 37)
>inp[0] *   
>/          //works as it should
>inp[0] /
>+          //problem!! if condition not entered even though it should 
            //as inp[0] == '+' (line 61)
>inp[0] +   //confirmation inp[0] is + right before if condition checked
>Segmentation fault (core dumped)

我尽我所能简要地解释了代码和问题,我问这个问题是因为这个问题对我来说完全不清楚,任何需要的解释都请告诉我

此外,请给出任何调试此类问题的建议,我以前也遇到过这样的错误,我不能每次都在这里问。为初学者->业余程序员提供任何建议,以解决此类分段错误

感谢并问候

一般建议:

使用ide提供的断点和其他功能来查找问题。

c++诞生已经几十年了,不会有这样的bug了。

diag:

对于调试消息,将cout<<"+ detected";更改为cout<<"+ detected"<<endl ;endl用于冲洗缓冲区并将其放到屏幕上。

它确实进入了你的if条件,并在失败

if (stk.top() == '*' || stk.top() == '/' && stk.size() != 0 )

如果stk.top()成功,当然是stk.size() != 0。它不是空的。

如果stk.empty() == truestk.top()将尝试从空堆栈中获取一些东西,并抛出seg错误。

就在下面几行,还有另一个if-statement也有同样的错误:

else if (stk.top() == '-' && stk.size() != 0 )

我更改了这些行,代码适用于您的输入序列1 3 * / +