1

这是我为学校科学博览会编写的代码示例。

#include <iostream>
#include <math.h>
using namespace std;

struct FUNC{
    char token;
    FUNC *left;
    FUNC *right;
};

double eval (FUNC *head){
    if (head->left==NULL){ 
        return atof(head->token); //this is where the error occurs
    }
}

void main(){
    FUNC node1= {'1',NULL,NULL};

    cout << eval(&node1)<< endl;

    system("pause");
}

当我运行此代码时,我收到此错误。

error C2664: 'atof' : cannot convert parameter 1 from 'char' to 'const char *'

谁能解释这个错误并给我一个如何补救的例子?

4

3 回答 3

2

这很简单。您正在将 char 传递给需要 char* 的函数。

struct FUNC{
    char token;
    FUNC *left;
    FUNC *right;
};

应该

struct FUNC{
    char* token;
    FUNC *left;
    FUNC *right;
};

当你在它的时候,你还必须初始化 char* 所以你必须做一个像

   FUNC* initFunc(const char* str,FUNC* left,FUNC* right)
   {
       // (FUNC*) is a cast to a type of pointer to FUNC. It is not needed if you write in C but 
       //since I saw cout in your code then if it's C++ you need to cast the results of malloc
       FUNC* ret = (FUNC*) malloc(sizeof(FUNC);
       int len = strlen(str);
       ret->str = malloc(len+1);
       strcpy(ret->str,str);
       ret->left = left;
       ret->right = right;
       return ret;
   }

所以最后在你的主要你会有这样的东西:

//please note the existence of " " since this is not a char but a string literal
FUNC* node1 = initFunc("1",NULL,NULL);

cout << eval(node1)<< endl;
于 2012-02-12T04:22:43.037 回答
1

一点建议,您应该包含标题 cmath 代替 math.h。引用GOTW

""命名空间规则 #3:使用新样式的 C 头文件 " #include <cheader>" 而不是旧样式 " #include <header.h>"。

为了与 C 向后兼容,C++ 仍然支持所有标准 C 头文件名称(例如,stdio.h),并且当您#include 那些原始版本时,相关的 C 库函数在全局命名空间中像以前一样可见——但在同样,C++ 还表示不推荐使用旧的标头名称,这让全世界都注意到它们可能会在 C++ 标准的未来版本中被删除。因此,标准 C++ 强烈鼓励程序员更喜欢使用以“c”开头并删除“.h”扩展名的新版本的 C 头文件(例如,cstdio);当您#include 使用新名称的 C 头文件时,您将获得相同的 C 库函数,但现在它们位于命名空间 std。" "

于 2012-02-12T04:43:52.580 回答
0

要获取单个字符的数值,只需使用:

c - '0'

不知道你为什么要使用atof一个不是小数的数字。将字符串解析为整数的首选函数通常应该是strtod,但如前所述,您甚至不需要一个字符。

于 2012-02-12T04:32:05.503 回答