【问题标题】:convert const char* to int将 const char* 转换为 int
【发布时间】:2015-11-23 03:28:02
【问题描述】:

我从 CSV 文件中读取 4 列(整数)。读取函数有效,但是当我尝试将 char 值插入(整数)数组时返回此错误

“const char *”类型的值不能分配给类型为实体的实体 “浮动”

我尝试使用 atoi 但返回 0000、1111 等列表。 你能给我一些解决方案吗? 代码:

const char* getfield(char* line, int num)
{
    const char* tok;
    for (tok = strtok(line, ",");
            tok && *tok;
            tok = strtok(NULL, ";\n"))
    {
        if (!--num)
            return (tok);
    }
    return NULL;
}


int main(void)
{

    FILE *pf=fopen("Trajectory_1.csv","r");         
    char line[1024];

    if(pf==NULL){
        printf("ERROR MESSAGE");
        exit(1);
    }
    int x=0;
    while(fgets(line,sizeof(line),pf)){
        char* tmp=strdup(line);
        printf("%s",getfield(tmp,1));
        t_h[x]=getfield(tmp,1);
        free(tmp);
        x++;
    }
    fclose(pf);
}

在这种情况下只有第一列

编辑 代码将是

double getfield(char* line, int num)
{
    const char* tok;
    for (tok = strtok(line, ","); //comam separator
            tok && *tok;
            tok = strtok(NULL, ";\n"))
    {
        if (!--num)
            return (atof(tok));
    }
    return NULL;
}

FILE *pf=fopen("//home//user//Documenti//Bello//Dataset1//Trajectories//Trajectory_1.csv","r"); //rivedere
    char line[1024];

    if(pf==NULL){
        printf("ERR MSG");  // I change this like William suggest
        exit(1);
    }

int x=0;

    while(fgets(line,sizeof(line),pf)){

        double d=getfield(line,1)); // I did not understand

    }
    fclose(pf);

【问题讨论】:

  • ` printf("ERROR MESSAGE");` 总是错误的。错误属于标准错误。试试pf = open( path, "r"); if( pf == NULL ) { perror( path ); ...
  • @WilliamPursell "Error Message" 只针对这个问题,我有适当的消息
  • 当然,但是您将其打印到错误的流中。
  • @WilliamPursell 好的,我将更改我的代码,谢谢
  • 我没有看到t_h 的声明,所以我认为它是一个浮点数组。如果没有显式转换,您无法进行该分配,但显式转换是错误的。更重要的是,您正在从 getfield 返回一个局部变量的地址,而该值在函数返回后是无用的。你想做什么?我怀疑您想在 getfield 中调用 strtod 并返回该值。

标签: c csv io


【解决方案1】:

getField是返回num标识的CSV列的浮点值。每次调用getField,并解析一个新行。

那么函数应该返回一个double,即return(atof(tok));(并声明为double getfield(..);

您必须删除您的 print 语句,因为它调用 getField 但 getField 修改了字符串(通过 strtok)。似乎也没有必要打电话给strdup;让 getField 在 line 上工作。

注意:我不是strtok 专家,但第二次调用(在 for 语句中)可能是错误的,并且可能还需要逗号作为终止符。

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 2013-10-16
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多