As variable my_double
is of type double
you will have to use %lf
instead of %f
. Also you missed &
(as rightly pointed out by Chris)
if (sscanf(tok, "%lf", &my_double) > 0)
Question
Im trying to convert a token to a float using sscanf. The code compiles and runs but whenever I enter a value I just get 0.0000. Its not converting properly for some reason.
Here's the code:
while(1)
{
printf("repl> ");
char *storage [30];
char *tok;
char g;
double my_double;
char buffer[20];
int pos = 0, i;
fgets(buffer,sizeof(buffer),stdin);
tok = strtok(buffer," ");
while (tok != NULL)
{
if (strcmp(tok, "add") == 0) printf("YES!!");
else if (strcmp(tok, "add\n") == 0) printf("YELZZ!!!");
if (strcmp(tok, "quit") == 0) exit(1);
else if (strcmp(tok, "quit\n") == 0) exit(1);
if (sscanf(tok, "%f", my_double) > 0)
{
Push(NULL, my_double, &head);
}
else
Push(strdup(tok), 0, &head);
tok = strtok(NULL," ");
}
Display(&head);
Solution
As variable my_double
is of type double
you will have to use %lf
instead of %f
. Also you missed &
(as rightly pointed out by Chris)
if (sscanf(tok, "%lf", &my_double) > 0)
OTHER TIPS
Try passing a pointer to the number into sscanf, rather than the number itself:
sscanf(tok, "%lf", &my_double);
The sscanf
function needs to know where to store the result, so passing in a copy of my_double won't work.
Additionally, as pointed out by Abhay, you need to specify "%lf%
as your format string if you're reading into a double.