阿托伊未正确转换字符串
atoi not converting string properly?
所以,我有以下(笨拙!)代码,用于中缀到后缀表达式转换器和计算器(正如我在上一篇文章中提到的:简单的数值表达式求解器,感谢大家!
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
stack<char> operators;
stack<char> output;
stack<char> temp;
stack<char> answer;
string command;
cout << "=>";
cin >> command;
// "Shunting Yard" algorithm
// source: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
for(int i=0; i<command.size(); i++)
{
switch(command[i])
{
case '*': case '+': case '-': case '/': case'(':
operators.push(command[i]);
break;
case ')':
while(operators.top() != '(')
{
output.push(operators.top());
operators.pop();
}
operators.pop();
break;
default:
output.push(command[i]);
break;
}
}
while(!operators.empty())
{
output.push(operators.top());
operators.pop();
}
while(!output.empty())
{
temp.push(output.top());
output.pop();
}
while(!temp.empty())
{
if(temp.top() == '+')
{
int a = atoi(&answer.top());
cout << "A=" << a << endl;
answer.pop();
int b = atoi(&answer.top());
cout << "B=" << b << endl;
answer.pop();
answer.push(b+a);
} else {
answer.push(temp.top());
}
temp.pop();
}
cout << answer.top() << endl;
system("pause");
return 0;
}
无论如何,问题是:例如,如果我输入 3+4,结果是"&",而正确的结果是"7"。那么,我的代码有什么问题呢?
这里有两个问题。
第一:
int a = atoi(&answer.top());
Atoi 获取指向以 null 结尾的字符串的指针。但是 &answer.top() 只是指向单个字符的指针。因此,atoi 将开始从该字符读取,然后继续浏览内存,直到找到"\0"字符(或非数字)。根据堆栈在您的平台上的实现方式,这可能意味着它读取"4",然后是"3",然后是"\0",因此它以"43"结尾。或者它可能会读取"4",然后读取一些恰好以"8675309j"开头的未初始化内存,因此它以"48675309"结尾。
如果你想知道为什么编译器没有警告你这个错误,问题是 C 风格的字符串和指向单个字符的指针在语法上是完全相同的类型 (char*),所以编译器无法告诉你它们混淆了,除非它理解 atoi 的语义。这是最好使用 C++ 字符串类和函数而不是基于 C char* 的函数的众多原因之一。
第二:
answer.push(b+a);
B+A 是一个 int,但你把它推到一堆字符中。因此,即使它具有正确的值,您也会推送字符"\007",而不是字符"7"。您需要重新串化它。但在这种情况下,你显然得到了类似 305419814 的东西,当转换为 char 时,它被截断为低 8 位 (38),而 38 是"&"。
替换这段代码:
if(temp.top() == '+')
{
int a = atoi(&answer.top());
cout << "A=" << a << endl;
answer.pop();
int b = atoi(&answer.top());
cout << "B=" << b << endl;
answer.pop();
answer.push(b+a);
}
跟:
if(temp.top() == '+')
{
int a = answer.top() - '0';
cout << "A=" << a << endl;
answer.pop();
int b = answer.top() - '0';
cout << "B=" << b << endl;
answer.pop();
answer.push(b+a);
}
将解决您的问题。
相关文章:
- wcstombs_s(),转换字符串的长度
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 无法转换字符串插入函数的参数
- 转换字符串向量:基于先前的值跳过元素
- 从中间器转换字符串不起作用,出了什么问题?
- 失败的证明转换字符串到枚举类
- 如何使用正则表达式和提升转换迭代器标记和转换 c 字符串
- 使用java jni时转换字符串类型
- 如何避免在转换字符串令牌流时重复istringstream构造
- 阿托伊未正确转换字符串
- C++,转换字符串,使连续下划线序列变为单个下划线
- 使用长算术转换字符串
- 转换字符串十进制数时的精度
- 将词法转换字符串提升为双精度
- 使用marshal_as函数转换字符串的性能
- C++不会从数据转换字符串
- 无论如何,在c++ /Qt中转换字符串到结构中的字段
- C++ 隐式类型转换字符串 -> int?
- 转换字符串到浮点数,c++实现
- 用于转换字符串大小写的函数