file io - converting a string to double using atof in c -
i trying read file , store in matrix using c. code have
readsparseinput (int nvtxs,int nsize, double vector[], int rowptr[] ,int colind [] , double values[]) { int index,row=0,column=0; int sparsity_value, nvtxs_local; int vector_size =50; double value; double randvect[vector_size]; int length=0; char buf[bufsiz]; file *fp; fp=fopen("/home/lopez380/parallel/m10-a.ij", "r"); index =0; nvtxs_local = 0; rowptr[0] = 0; char *p1; while ( !feof(fp)) { // null buffer, read line buf[0] = 0; fgets(buf, bufsiz, fp); // if it's blank line, ignore if(strlen(buf) > 1) { p1 = strtok(buf, " "); row=atoi(p1); #ifdef debug fprintf(stdout, "row : %d ", row); #endif p1 = strtok(null, " "); column=atoi(p1); #ifdef debug fprintf(stdout, "column : %d ", column); #endif p1 = strtok(null, " "); value=atof(p1); #ifdef debug fprintf(stdout, "value : %g\n ", value); #endif } } fclose(fp); #ifdef debug printf("lfilelen = %d\n", length); #endif }
the code works when take p1 , convert integer using atoi. when use atof convert value float, getting zero. input looks like
0 0 1.76420546156578 0 3 -4.80876443295632 0 6 1.20260376970926 0 9 3.30693451100554 1 1 1.13901264701619 1 4 0.370358438592131 1 7 -0.551593262343761
after read input, when print getting
row : 0 column : 0 value : 0 row : 0 column : 3 value : 0 row : 0 column : 6 value : 0 row : 0 column : 9 value : 0 row : 1 column : 1 value : 0 row : 1 column : 4 value : 0 row : 1 column : 7 value : 0
when use atoi , following
row : 0 column : 0 value : 1 row : 0 column : 3 value : -4 row : 0 column : 6 value : 1 row : 0 column : 9 value : 3 row : 1 column : 1 value : 1 row : 1 column : 4 value : 0 row : 1 column : 7 value : 0
can please me?
i discourage using atoi() , atof(), unless implementation provides error checking (e.g. atoi() , atof()" update errno.
i prefer fscanf(): illegal input can detected return value.
example:
if (fscanf(fp, "%f", &f) == 1) ...all ok... else ...eof or conversion failure...
Comments
Post a Comment