C++反向波兰符号堆栈

C++ Reverse Polish Notation Stack

本文关键字:符号 堆栈 C++      更新时间:2023-10-16

我正在处理一个项目,该项目要求我接受用反向抛光表示法编写的字符串,并使用堆栈对其进行评估。我应该遍历字符串,如果元素是一个数字,我会一直遍历字符串,直到到达一个空格,然后使用atoi将字符串的这一部分转换为整数。然后我把那个整数推到堆栈上。我的代码是有效的,但是,我不确定如何继续到空格后的下一个数字。这是我迄今为止的for循环:

for (unsigned int i = 0; i < a.size(); i++)
{
    int b;
    char c[a.size()];
    while (isdigit(a[i]))
    {
        cout << a[i] << endl;
        c[i] = a[i];
        b = atoi(c);
        i++;
    }
    cout << b << endl;
    stack.push(b);
}

这总是将第一个整数推送到堆栈上,即使在一个空格之后还有更多整数。我需要添加什么才能在空格后继续将整数推送到堆栈中?谢谢你的帮助。

您的问题在这里:

c[i] = a[i];

读取第二个整数时,您将使用当前的i,而不是在数组c的开头写入数字。对atoi(c)的调用将看到第一个未覆盖的整数,并返回该值。

您应该使用第二个索引将数字放在c数组中,并在堆栈上推送整数后重置第二个指数。

以下是一个示例(未测试):

unsigned j = 0;
char c[a.size()+1];
for (unsigned int i = 0; i < a.size(); i++)
{
    int b;
    while (isdigit(a[i]))
    {
        cout << a[i] << endl;
        c[j] = a[i];
        j++;
        i++;
    }
    c[i] = '';
    b = atoi(c);
    cout << b << endl;
    stack.push(b);
    j = 0;
}

我想这是一些家庭作业,你必须按照自己的方式工作。在惯用语C++中,人们会使用字符串流来完成这项工作。

#include <sstream>
int b;
std::stringstream buffer(a);
while(buffer >> b) {
    stack.push(b);
}