Hello all, I was trying this problem of checking if the input integers can be ordered using the STL implementation of the stack. The program reads from a file named "input.txt" which in its first line has the number of integers that follow in the second line. The second line integers are the ones that are to be ordered. My code:
#include<iostream>
#include<cstdlib>
#include<stack>
#include<fstream>
using namespace std;
int main()
{
stack<int> st;
int no,temp,last=1,x;
bool startfound=false,possible=true;
ifstream in("input.txt");
if(!in) {
cout<<"No such file"<<endl;
exit(EXIT_SUCCESS);
}
in>>no;
while(no){
last=1;
startfound=false;
possible=true;
while(!startfound){
in>>temp;
cout<<temp<<" "<<startfound;
if(temp==1) {
startfound=true;
} else{
st.push(temp);
}
no--;
// getchar();
}
cout<<"stack size:"<<st.size()<<endl;
//getchar();
while(no--){
in>>temp;
if(temp-last != 1){
x=st.top();
if(x-last ==1) {
last=st.top();
st.pop();
}else{
possible=false;
break;
}
}
else
last=temp;
}
while(st.size()>0 && possible == true ){
if(st.top()-last == 1){
last=st.top();
st.pop();
}else{
possible=false;
}
}
if(possible == false){
while(no--) {
in>>temp;
}
while(st.size() > 0)
st.pop();
}
}
in.close();
possible?cout<<"true":cout<<"false";
return 0;
}
But unfortunately in the initial stage of debugging I came across two problems.
1. The "in>>temp" statement does not acknowledge the numbers 2,3,4 and goes to 5 and enters into a infinite loop. The input.txt contained:
5
1 2 3 4 5
(I noticed that when i made the data set like this:
5
12 3 4 5 6
all the numbers were acknowledged thereby exiting the while loop.)
2. The "x=st.top();" statement in line number 39 is showing up in the stacktrace after a segmentation fault occurs. This was due to the dataset:
5
2 1 3 4 5
Can you please explain these errors to me. This is my first post in this forum and I may sound naive. So, please be patient with me. Thank you in advance.