C++反向波兰符号堆栈
C++ Reverse Polish Notation Stack
我正在处理一个项目,该项目要求我接受用反向抛光表示法编写的字符串,并使用堆栈对其进行评估。我应该遍历字符串,如果元素是一个数字,我会一直遍历字符串,直到到达一个空格,然后使用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);
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- vscode g++链路故障:体系结构x86_64的未定义符号
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- 将大双精度转换为无符号 int 期间堆栈损坏
- 使用C 中的堆栈匹配相同的符号
- 当程序与符号名称一起崩溃时,输出呼叫堆栈
- GDB正在调试一个缺少特定调用堆栈的符号表的核心转储
- 双精度为“无符号长长”会导致内存(堆栈?)损坏
- 在 C++/STL/MFC 应用程序启动早期发生的致命异常中,是否可以信任堆栈回溯符号名称?
- 为什么 UMDH 找不到我的符号?我可以在没有它们的情况下解释堆栈跟踪吗?
- 体系结构x86_64的未定义符号:构建堆栈
- c++和VS2010-没有为任何调用堆栈帧加载符号.无法显示源代码
- C++反向波兰符号堆栈
- 符号如何影响调用堆栈遍历
- 没有为任何调用堆栈帧加载符号.无法显示源代码