这是我为学校科学博览会写的代码样本。
#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 *'谁能解释这个错误,并给我一个如何纠正它的例子?
发布于 2012-02-12 12:22:43
这很简单。您正在将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;
}最后,在你的main中,你会得到类似这样的东西:
//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-12 12:43:53
一点建议,您应该在math.h中包含cmath头文件。引用GOTW
“”命名空间规则#3:使用具有新样式"
#include <cheader>“的C标头,而不是旧样式"#include <header.h>”。
为了向后兼容C,C++仍然支持所有的标准C头名称(例如,stdio.h),并且当您#包含这些原始版本时,相关的C库函数将像以前一样在全局名称空间中可见--但与此同时,C++还说旧的头名称已被弃用,这让人们注意到,它们可能会在C++标准的未来版本中被删除。因此,标准C++强烈鼓励程序员更喜欢使用以"c“开头并去掉".h”扩展名的新版本的C头文件(例如,cstdio);当您使用新名称#包括C头文件时,您将获得相同的C库函数,但它们现在位于名称空间std中。“"
发布于 2012-02-12 12:32:06
要获取单个字符的数值,只需使用:
c - '0'我不确定为什么要使用atof,因为它是一个不是小数的数字。选择将字符串解析为整数的函数通常应该是strtod,但如前所述,使用一个字符甚至不需要该函数。
https://stackoverflow.com/questions/9246422
复制相似问题