首页 > 解决方案 > 有什么方法可以使用 strtof() 来转换“负数”?

问题描述

我正在尝试编写一个函数来将字符串转换为数学运算。


int RPN_Evaluate(char * rpn_string, double * result)
{
   struct Stack calculate = {};
   char *token;
   char *endptr;
   double x,y;

   token = strtok(rpn_string, " ");
    while (token != NULL) {
        *number = strtof(token, &endptr);
        if (*token == '+') {
            StackPop(&calculate, &y);
            StackPop(&calculate, &x);
            result_operation = x + y;
            StackPush(&calculate, result_operation);
        } else if (*token == '-') {
            StackPop(&calculate, &y);
            StackPop(&calculate, &x);
            result_operation = x - y;
            StackPush(&calculate, result_operation);
        }else if (*endptr != NULL) {
            return RPN_ERROR_INVALID_TOKEN;
        } else if (*endptr == NULL) { 
            StackPush(&calculate, *number);
        }
        token = strtok(NULL, " ");
   }

    StackPop(&calculate, result);
    return RPN_NO_ERROR;
}

如果我传入 "1 1 +" ,它工作得很好。但是,当我传入“2 -1 +”时遇到问题有什么办法可以使用 strtof() 将“-1”转换为 -1?strtof() 似乎不会自动执行此操作。

标签: cstring

解决方案


推荐阅读