阿托伊未正确转换字符串

atoi not converting string properly?

本文关键字:转换 字符串      更新时间:2023-10-16

所以,我有以下(笨拙!)代码,用于中缀到后缀表达式转换器和计算器(正如我在上一篇文章中提到的:简单的数值表达式求解器,感谢大家!

#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);
    } 

将解决您的问题。