I read from CSV file with 4 column (integers). The read function works but when I try to insert char values into array (of integers) return this error
a value of type "const char *" cannot be assigned to an entity of type "float"
I try to use atoi
but return list of 0000, 1111 etc. Can you suggest me some solution? the code:
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);
}
in this case only the first column
EDIT the code will be
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);
getField
is to return the floating point value of the CSV column identified by num
. getField
is called each time with a new line to parse.
Then the function should return a double, namely return(atof(tok));
(and be declared as double getfield(..
);
You must remove your print statement, as it calls getField
but getField modifies the string (through strtok). Also there seems no need to call strdup
; just let getField work on line
.
Note: I am not a strtok
specialist but the second call (in the for statement) may be wrong and may also need the comma as a terminator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.