堆栈上的前缀到中缀
我正在尝试在 C++ 中实现前缀到中缀,这就是我到目前为止所得到的。例如,输入应该是这样的:
/7+23
输出:
7/(2+3) or (7/(2+3))
但我得到的是:
(/)
这是我到目前为止编写的代码:
void pre_to_in(stack<char> eq) {
if(nowe.empty() != true) {
char test;
test = eq.top();
eq.pop();
if(test == '+' || test == '-' || test == '/' || test == '*') {
cout << "(";
pre_to_in(eq);
cout << test;
pre_to_in(eq);
cout << ")";
} else {
cout << test;
}
}
}
// somewhere in main()
char arr[30];
stack<char> stosik;
int i = 0;
cout << "write formula in prefix notation\n";
cin >> arr;
while(i < strlen(arr)) {
stosik.push(arr[i]);
i++;
}
pre_to_in(stc);
I'm trying to implement prefix to infix in c++, that's what i've got so far. The input should be for example something like this:
/7+23
And the ouput:
7/(2+3) or (7/(2+3))
But instead I get:
(/)
That's the code I wrote so far:
void pre_to_in(stack<char> eq) {
if(nowe.empty() != true) {
char test;
test = eq.top();
eq.pop();
if(test == '+' || test == '-' || test == '/' || test == '*') {
cout << "(";
pre_to_in(eq);
cout << test;
pre_to_in(eq);
cout << ")";
} else {
cout << test;
}
}
}
// somewhere in main()
char arr[30];
stack<char> stosik;
int i = 0;
cout << "write formula in prefix notation\n";
cin >> arr;
while(i < strlen(arr)) {
stosik.push(arr[i]);
i++;
}
pre_to_in(stc);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个堆栈。先入后出。您需要反向输入字符串“32+7/”。
您使用了很多堆栈。每次进入 pre_to_in() 时都会复制堆栈。使用引用或指针,例如:
void pre_to_in(stack&eq);
就这样。
PS统一名称(s/nowe/eq/g && s/stc/stosik/g)
This is a stack. First in, last out. You need reverse input string "32+7/".
You use many stacks. In every enter to pre_to_in() stack is copied. Use reference or pointer, ex:
void pre_to_in(stack<char> &eq);
Thats all.
P.S. Unify names (s/nowe/eq/g && s/stc/stosik/g)
只读取输入的一个“单词”,而不是一整行。这里它只获取第一个斜杠字符。
only reads one "word" of input, not a whole line. Here it's only getting the first slash character.
不确定您是否正在寻找这样的解决方案,无论如何,对于您提到的输入,它给出了您发布的输出,
它从 std 输入读取令牌
我现在已经在 Visual Studio 2005 下构建了它 - 要终止输入,请按 Enter,Ctrl+ Z, Enter
但在其他编译器上终止可能会以另一种方式工作
not sure if you are looking for such solution, anyway for the input you've mentioned it gives the output from you post
it reads tokens from std input
I've built it now under Visual Studio 2005 - to terminate input press Enter, Ctrl+Z, Enter
but on other compilers termination may work in another way