Reputation: 1617
Calling strtof
with a floating point number runs fine on my local machine but on the school's servers strtof always returns 0.000000
. I checked to see if there was anything stored in errno
since a 0 should mean an error, but it says success. Does anyone have an idea why this might be?
Here is the code.
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%f\n", strtof(argv[1],0));
return 0;
}
Upvotes: 1
Views: 1697
Reputation: 14014
Short version: compile with -std=gnu99
or -std=c99
. Explanation follows.
I've reproduced a similar "problem" on my own box. However, when I try to compile:
# gcc -Wall -o float float.c
float.c: In function 'main':
float.c:6: warning: implicit declaration of function 'strtof'
float.c:6: warning: format '%f' expects type 'double', but argument 2 has type 'int'
So I looked at the man
page for strtof()
, and it says:
SYNOPSIS
#include <stdlib.h>
double strtod(const char *nptr, char **endptr);
#define _XOPEN_SOURCE=600 /* or #define _ISOC99_SOURCE */
#include <stdlib.h>
float strtof(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr);
What that means is that one of those values has to be #define
d before including stdlib.h
. However, I just recompiled with -std=gnu99
, and that defines one of those for me and it works.
# gcc -std=gnu99 -Wall -o float float.c
# ./float 2.3
2.300000
Moral: always compile with -Wall
. ;-)
Upvotes: 5
Reputation: 36082
Have you included the header where strtof is defined (stdlib.h), otherwise you may get 0.0 since by default unknown functions in C are treated as returning int.
Upvotes: 2