【问题标题】:C++ Reverse Polish Notation StackC++ 逆波兰符号堆栈
【发布时间】:2016-03-02 00:56:21
【问题描述】:

我正在做一个项目,该项目要求我接受一个用反向波兰表示法编写的字符串并使用堆栈对其进行评估。我应该遍历字符串,如果元素是数字,我会继续遍历字符串,直到找到一个空格,然后使用 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++ arrays string class stack


【解决方案1】:

你的问题在这里:

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] = '\0';
    b = atoi(c);
    cout << b << endl;
    stack.push(b);
    j = 0;
}

我认为这是一些家庭作业,您必须按照自己的方式工作。在惯用的 C++ 中,人们会使用 stringstream 来完成这项工作。

#include <sstream>

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

【讨论】:

  • 嗯,有道理。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 2016-12-09
相关资源
最近更新 更多