0

My C is rusty. I am trying to convert a string to float (or double). I have tried atof() and strtof(), and tried following instructions here and here. No luck.

Here's my code:

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

int main(int argc, char *argv[]) {
  float x;
  char a[20];
  strcpy(a,argv[1]);
  x = strtof(a);
  printf("%s\n",a);
  printf("%f\n",x);
  return 0;
}

No luck. Here's output, on the command line:

prompt$ ./a.out 2.34
2.34
1426063.000000
prompt$

If I use atoi() instead, I get 0.0.

Clearly there is something simple I'm missing. This is with gcc 4.8.4 on ubuntu fwiw.

Makes no difference if I compile with -static flag, or use double instead of float (and %e instead of %f), or include math.h. The output changes in some of those cases, but it's still nonsense.

Thanks, Peter

Community
  • 1
  • 1
mrentropy
  • 57
  • 1
  • 3
  • Possible duplicate of [Convert string to float in Objective-C](http://stackoverflow.com/questions/3191034/convert-string-to-float-in-objective-c) – Draco18s no longer trusts SE Dec 09 '15 at 20:11
  • 5
    Did you disable warnings or what? The prototype for `strtof()` looks rather different than what you seem to think. – EOF Dec 09 '15 at 20:11

1 Answers1

4

You haven't included <stdlib.h> to get strtof()'s prototype. So the return type defaults to int. But implicit int rule has been removed from C since C99.

The usage is also wrong. It should be, at least:

char *eptr;

x = strtof(a, &eptr);

And inspect eptr for conversion failures.

Compile with warnings enabled. GCC warns with:

warning: implicit declaration of function ‘strtof’ [-Wimplicit-function-declaration]

P.P
  • 117,907
  • 20
  • 175
  • 238
  • OK thanks. I hadn't disabled warnings, and I didn't get one, but that was clearly the problem. Including stdlib.h, and adding a second argument "NULL" to strtof(), together fixed it. However, I think the usage of strcpy() was actually correct; argv[1] is already a pointer. – mrentropy Dec 09 '15 at 20:35
  • 1
    Ooops, you meant the usage of strtof(), not strcpy(). Yes, you are right, my usage of strtof() was incorrect (sigh). – mrentropy Dec 09 '15 at 20:47