请帮我解决以下 spoj 表达式转换问题 here is the link 。它给出了运行时错误。
#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;
}
}
出现的错误是无法理解的。 以下是第一行和第二行输入的错误。
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
最佳答案
看来您已成为 Java 主义的受害者。
char ch = 'a';
string str = value + "";
不会使字符串str
“a”。
这是因为 ""
不是 字符串
。它实际上是一个指向常量字符数组的指针,即 const char *
,并且因为它是一个指针,所以会进行指针算术。
""
是内存中的某个位置。假设地址 10000。'a'
有一个数值。让我们坚持使用 ASCII 并使用 97。 value + "";
告诉编译器转到地址 10000 + 97,没有人知道它会在地址 10097 找到什么。但它是一个 const char *
和 string
有一个构造函数,它将接受 const char *
并尝试将其转换为 string
。无论 10097 处发生什么,都将用于生成该字符串
。这可能会使程序崩溃。它还可能从字符串文字中获取垃圾,这看起来就是 OP 所发生的情况。
解决方案:
构造一个字符串
。
string str(1, ch);
或者就OP而言,
st.push(string(1, s.at(i)));
Documentation on string
constructor请参阅构造函数 2。
但是要小心。你还有一堆其他逻辑错误best resolved by using the debugging software几乎肯定是您的开发环境附带的。
关于c++ - C++ 中的运行时错误。重定位协议(protocol)版本 %d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41053822/