2015-08-28 268 views
0

我從具有4列(整數)的CSV文件讀取。讀取功能的工作原理,但是當我嘗試插入字符值到陣列(整數)返回該錯誤將const char *轉換爲int

類型的值「爲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); 
} 

在這種情況下,只有第一列

EDIT 代碼將是

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); 
+0

'printf(「ERROR MESSAGE」);'總是錯的。錯誤屬於stderr。嘗試'pf = open(path,「r」); if(pf == NULL){perror(path); ...' –

+0

@WilliamPursell「錯誤信息」僅限於此問題,我有適當的信息 –

+0

當然,但是您將它打印到錯誤的流中。 –

回答

0

getField是返回所標識的CSV列的浮點值通過num。每次用一個新行來調用getField進行解析。

然後函數應該返回一個double,即return(atof(tok));(並聲明爲double getfield(..);

您必須刪除打印語句,因爲它調用getField,但getField會修改字符串(通過strtok)。也似乎沒有必要撥打strdup;只要讓getField在line上工作即可。

注意:我不是strtok專家,但第二個調用(在for語句中)可能是錯誤的,也可能需要逗號作爲終止符。