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

Dani AI

Generated

Two separate bugs explain the “weird” results: a buffer/size mismatch when reading lines and a wrong pointer type assignment, both leading to undefined behavior. As hinted, the size passed to the read function must match the actual buffer. Also, assigning the return value of a string function (which is char *) to a variable declared as double * will corrupt memory. 's idea to use formatted parsing is valid, but prefer robust conversion with error checking.

A safe pattern: read each full line into a properly sized buffer, extract the first token, and convert it with strtod while checking errno and endptr. This avoids atof (which gives no error reporting) and prevents overruns. Example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main(void) {
    char line[128];
    FILE *fp = fopen("square10.dat", "r");
    if (!fp) return 1;
    while (fgets(line, sizeof line, fp)) {
        char *token = strtok(line, " \t\r\n");
        if (!token) continue;
        errno = 0;
        char *endptr;
        double x = strtod(token, &endptr);
        if (endptr == token || errno == ERANGE) {
            fprintf(stderr, "bad numeric token: %s\n", token);
            continue;
        }
        printf("%.6f\n", x);
    }
    fclose(fp);
    return 0;
}

Checklist and quick tips: always use sizeof buffer with fgets; declare string pointers as char *; prefer strtod + endptr/errno over atof; sscanf can work for simple fixed formats but still needs validation; remove system("pause") for portable code. See the standard references for details: fgets, strtok, .

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.