Please help me with following problem of transforming expression of spoj here is the link. It is giving runtime error.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
int testcases;
cin >> testcases;
while(testcases-->0)
{
string s;
cin >> s;
cout << s;
stack<string> st;
for(int i=0;i<s.length();i++)
{
if(s.at(i)=='(')
continue;
else
if(s.at(i)==')')
{
string s2=st.top();
st.pop();
string expression=st.top();
st.pop();
string s1=st.top();
st.pop();
string tba=s1+s2+expression+"";
st.push(tba);
cout << tba << endl ;
}
else
st.push(s.at(i)+"");
}
string ss=st.top();
cout << ss;
}
}
And the error coming is not understandable. following is the error with input in first and second line.
1
(a+(b*c))
(a+(b*c))do relocation protocol version %d.
o relocation protocol version %d.
uery failed for %d bytes at address %p
udo relocation protocol version %d.
do relocation protocol version %d.
o relocation protocol version %d.
uery failed for %d bytes at address %pery failed for %d bytes at address %p
udo relocation protocol version %d.
do relocation protocol version %d.
o relocation protocol version %d.
uery failed for %d bytes at address %pery failed for %d bytes at address %p
Looks like you've fallen victim to a Java-ism.
char ch = 'a';
string str = value + "";
does not make string str
"a".
This is because ""
is not a string
. It's actually a pointer to a constant character array, a const char *
, and because it is a pointer, pointer arithmetic takes place.
""
is some place in memory. Let's assume address 10000. 'a'
has a numerical value. Let's stick with ASCII and use 97. value + "";
is telling the compiler to go to address 10000 + 97, and nobody knows what it will find at address 10097. But it is a const char *
, and string
has a constructor that will take a const char *
and try to turn it into a string
. Whatever happens to be at 10097 will be used to make that string
. This could crash the program. It could also grab garbage from the land of the string literals, and this looks to be what's happening to OP.
Solution:
Construct a string
.
string str(1, ch);
or in OP's case,
st.push(string(1, s.at(i)));
Documentation on string
constructor See constructor 2.
But watch out. You have a bunch of other logic errors best resolved by using the debugging software that almost certainly came with your development environment.