程序没有进入如果条件,给出分段错误
program doesnt enter if condition , gives segmentation fault
代码有点像
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() == true
,stk.top()
将尝试从空堆栈中获取一些东西,并抛出seg错误。
就在下面几行,还有另一个if-statement
也有同样的错误:
else if (stk.top() == '-' && stk.size() != 0 )
我更改了这些行,代码适用于您的输入序列1 3 * / +
。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?