-3

I want to convert a char to a float in language C. But atof() and strtof() are not working.

Here is some code, maybe someone could help me! The difficulty is that my number has a e-02 included

char temp = "6.345e-02"; // the original value is read from a file
float result;

result = atof(temp); //not working correct
result = strtof(temp, NULL); //also not working correct

edit: new code

FILE *file = fopen("file.txt", "r");
char c;
char *temp[11];
float result;
while((c=fgetc(file))!=EOF){
  if(c=='\t'){
    result = atof(temp); //here is the converting problem
    printf("%.6f\n", result);
  } else {
    temp[i] = c;
  }
}
Gre Gor
  • 1
  • 2

2 Answers2

1

You're declaring temp as a single character which is not. It's a character array so it must be declared as char *temp instead.

Ahmed Karaman
  • 523
  • 3
  • 12
1

I ran this on IDEOne, and found that if I don't #include <stdlib.h>, I got incorrect results

#include <stdio.h>
//#include <stdlib.h>            // <== This line is crucial

int main(void) {
    char* temp   = "6.345e-2";
    float result = atof(temp);

    printf("%f\n", result);

    return 0;
}

With stdlib.h:

Success #stdin #stdout 0s 9424KB
0.063450

Without stdlib.h:

Success #stdin #stdout 0s 9424KB
0.000000
abelenky
  • 63,815
  • 23
  • 109
  • 159