my problem is quiet similar, i used atof here my data and code:

"square10.dat"
0.01 1:0.1
0.04 1:0.2
0.09 1:0.3
0.16 1:0.4
0.25 1:0.5
0.36 1:0.6
0.49 1:0.7
0.64 1:0.8
0.81 1:0.9
1.00 1:1.0

THE CODE:

#include <stdio.h>

int main() {
  char c[10];  /* declare a char array */
  int i;
  double *z,tmp1;
  FILE *file;  /* declare a FILE pointer  */

  file = fopen("square10.dat", "r"); 
  /* open a text file for reading */

  if(file==NULL) {
    printf("Error: can't open file.\n");
    /* fclose(file); DON'T PASS A NULL POINTER TO fclose !! */
    return 1;
  }
  else {
    printf("File opened successfully. Contents:\n\n");
    
    i=0;
    while(fgets(c, 25, file)!= NULL) 
    { 
      z= strtok (c, " ");
      /* keep looping until NULL pointer... */
      printf("String c[%i]: %s\n",i,z);        
      /* print the file one line at a time  */
      float tmp1 = atof(z);
      printf("Convert c[%i]: %.6f\n",i,tmp1);
      i=i+1;
    }

    printf("\n\nNow closing file...\n");
    fclose(file);
    system("pause");
    return 0;
  }
}

my goal is to pick the the first float number 0.01;0.04...1.00 and calculate it with certain formula (the formula not provide yet here).
i try to separate it first from 2nd string using strtok.
Since in my opinion the first number is in string format than i used atof to convert it to float.
But the result is weird. Would you help me with this problem?

Here the result so far:
String c[0] = 0.01
Convert c[0] = 2293488.000000
String c[1] = 0.04
Convert c[1] = 2293488.000000
String c[2] = 0.09
Convert c[2] = 2293488.000000
......
String c[9] = 1.00
Convert c[9] = -1.#J

Recommended Answers

All 3 Replies

> char c[10]; /* declare a char array */
...
> while(fgets(c, 25, file)!= NULL)
Do you know why you said 25 here?
Do you know why you should have said 10?

You could actually solve this problem using the fgets and sscanf function. These two function would do all things which you are looking for. Perhaps, you will have answer the Salem's question for you could implement it.

ssharish

> char c[10]; /* declare a char array */
...
> while(fgets(c, 25, file)!= NULL)
Do you know why you said 25 here?
Do you know why you should have said 10?

heh nice, here I was ready to give you both barrels about the behaviour of fgets() and then I re-read the code, classic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.