Solved

atof() and sscanf() do not work for me

Posted on 2002-07-09
3
409 Views
Last Modified: 2009-12-16
I'm trying to convert a string into a double.  I've tried both the atof() and sscanf() functions with no success.  What am I doing wrong?

I am running on a Solaris 2.8 UNIX box.

Here is the code:

#include <stdio.h>
#include <string.h>
main() {
  char numstring[] = "12.34";
  double d;
  d = atof(numstring);
  printf("String = %s\n",numstring);
  printf("Double = %f\n",d);
}

Here are the results:

String = 12.34
Double = -4264242.000000

Playing around with the format string in the second printf statement seems to change the answer, but not to 12.34.

Using sscanf() instead of atof() yields different incorrect results.

Any ideas?
0
Comment
Question by:dastrw
3 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 50 total points
Comment Utility
#include <stdlib.h>
0
 
LVL 30

Expert Comment

by:SteveGTR
Comment Utility
You should be using the long float formater for the seconds printf:

#include <stdio.h>
#include <string.h>
main() {
 char numstring[] = "12.34";
 double d;
 d = atof(numstring);
 printf("String = %s\n",numstring);
 printf("Double = %lf\n",d);  // %f should be %lf
}

Good Luck,
Steve
0
 
LVL 2

Author Comment

by:dastrw
Comment Utility
Thanks.  I must have zoned and thought stdio.h was the same as stdlib.h!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now