Library Function for converrting double to string

S

santosh

Sanchit said:
Library Function for converrting double to string in GCC.

sprintf and snprintf are both standardised and will both do the job,
though the latter will require C99 support and hence is less portable
than the former, but it avoids the buffer overflow problem of sprintf.
 
M

Martin Ambuhl

Sanchit said:
Library Function for converrting double to string in GCC.

Look up sprintf() and snprintf().

Those should be in any elementary C textbook.

In addition to checking your textbook before posting, it is a good idea
to check the C language FAQ <http://c-faq.com/>. Steve Summit put a lot
of effort into producing it, and many people get upset if posters don't
expend the tiny bit of effort it takes to consult it.

In this case, you might start with question 13.1
<http://c-faq.com/lib/itoa.html>. Everything that follows is from that
question and answer, but note the crossreferences to questions 7.5a,
8.6, 12.21, and 20.10, which you will need to check for yourself:

comp.lang.c FAQ list · Question 13.1

Q: How can I convert numbers to strings (the opposite of atoi)? Is there
an itoa function?

A: Just use sprintf:

sprintf(string, "%d", number);

(Don't worry that sprintf may be overkill, potentially wasting run time
or code space; it works well in practice.) See also the examples in the
answer to question 7.5a, and also questions 8.6 and 12.21.

You can obviously use sprintf to convert long or floating-point numbers
to strings as well (using %ld or %f); in other words, sprintf can also
be thought of as the opposite of atol and atof. In addition, you have
quite a bit of control over the formatting. (It's for these reasons that
C supplies sprintf as a general solution, and not itoa.)

If you simply must write an itoa function, here are some things to consider:

* There is a sample implementation in K&R.
* You'll have to worry about return buffer allocation; see question
7.5a.
* A naïve implementation usually doesn't handle the most-negative
integer (INT_MIN, usually -32,768 or -2,147,483,648) properly.

See also questions 12.21 and 20.10.

References: K&R1 Sec. 3.6 p. 60
K&R2 Sec. 3.6 p. 64
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,122
Messages
2,570,716
Members
47,282
Latest member
hopkins1988

Latest Threads

Top