473,394 Members | 1,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

sprintf function

Hi all,

I am new to c and trying the sprintf function.

I have written a testing program to try the sprintf fuction and expect
the output is 1.234. However, the output shows nothing.

Am I missing sth here?

Thanks in advance for you inputs.

Earth

#include <stdio.h>
char* toString(double d)
{
char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}

main()
{
printf("%s\n", toString(1.234));
}
Nov 14 '05 #1
15 26727
Earth wrote:
#include <stdio.h>
char* toString(double d)
{
char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}

main()
{
printf("%s\n", toString(1.234));
}


What do you suppose happens to buffer[9] when you return from
toString()?

(BTW toString is not a valid identifier)

--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c
Read my lips: The apple doesn't fall far from the tree.

Nov 14 '05 #2
In article <ab**************************@posting.google.com >, ea******@yahoo.com.hk (Earth) wrote:
I have written a testing program to try the sprintf fuction and expect
the output is 1.234. However, the output shows nothing. #include <stdio.h>
char* toString(double d)
{
char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}


The problem is with 'buffer' being local to the toString function.

See http://www.eskimo.com/~scs/C-faq/q7.5.html

Ian.
Nov 14 '05 #3
nrk
Earth wrote:
Hi all,

I am new to c and trying the sprintf function.

I have written a testing program to try the sprintf fuction and expect
the output is 1.234. However, the output shows nothing.

Am I missing sth here?

Thanks in advance for you inputs.

Earth

#include <stdio.h>
char* toString(double d)
{
char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}

main()
{
printf("%s\n", toString(1.234));
}


Congratulations!! You hit the FAQ jackpot. In fact, we even have an FAQ
that actually uses sprintf while answering your very question. You can
find this question and answer at:

http://www.eskimo.com/~scs/C-faq/q7.5.html

Please to take the time to go through the fine FAQ. It's available at:

http://www.eskimo.com/~scs/C-faq/top.html

-nrk.

--
Remove devnull for email
Nov 14 '05 #4
"Morris Dovey" <mr*****@iedu.com> wrote:

<snippage>
(BTW toString is not a valid identifier)


Why?
Nov 14 '05 #5

"Peter Pichler" <pi*****@pobox.sk> wrote in message
news:40**********@mk-nntp-2.news.uk.tiscali.com...
"Morris Dovey" <mr*****@iedu.com> wrote:

<snippage>
(BTW toString is not a valid identifier)


Why?


Can't start with "to". It's reserved for things like tolower, toupper,
etc...

Technically it's not "buggy C" just not portable. Just like using "errno"
for a local variable isn't a great idea neither.

Tom
Nov 14 '05 #6
"Tom St Denis" <to*@securescience.net> wrote in message
news:_7********************@news04.bloor.is.net.ca ble.rogers.com...
"Peter Pichler" <pi*****@pobox.sk> wrote in message
news:40**********@mk-nntp-2.news.uk.tiscali.com...
"Morris Dovey" <mr*****@iedu.com> wrote:

<snippage>
(BTW toString is not a valid identifier)
Why?


Can't start with "to".


....and a lowercase letter.
It's reserved for things like tolower, toupper,
etc...
But not toString. 'S' is not a lowercase letter, AFAICS.
Technically it's not "buggy C" just not portable. Just like using "errno"
for a local variable isn't a great idea neither.


Not only is it portable, it is also recommended. Either that or is_string().

Peter
Nov 14 '05 #7
On 8 Feb 2004 06:51:20 -0800, ea******@yahoo.com.hk (Earth) wrote:
I am new to c and trying the sprintf function.

I have written a testing program to try the sprintf fuction and expect
the output is 1.234. However, the output shows nothing.

Am I missing sth here?

#include <stdio.h>
char* toString(double d)
{
char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}


I see several problems:

1. %lf is not a valid specifier for sprintf; you want %f, which works
for both float and double types. Many implementations will let you get
away with this, but you should get in the habit of using the right one.

2. The buffer allows for only 8 characters in the representation of the
number. If the number has more digits than that, things could get ugly.

3. You're returning a pointer to a buffer that goes away when the
function returns, which will have unpredictable consequences. The
program could just as well have aborted. This is the one that is the
immediate issue.

There are several solutions to this last problem. One is to declare
buffer as static char so that it remains after the function exits;
another is to use the malloc() function to allocate the memory instead
and return a pointer to that memory; yet another is to allocate the
buffer in the main program and pass a pointer to that buffer to the
function and store the result there. Any of these will work for toy
programs, but the last two are generally better choices for real code.

--
Eric Amick
Columbia, MD
Nov 14 '05 #8
nrk
Tom St Denis wrote:

"Peter Pichler" <pi*****@pobox.sk> wrote in message
news:40**********@mk-nntp-2.news.uk.tiscali.com...
"Morris Dovey" <mr*****@iedu.com> wrote:

<snippage>
> (BTW toString is not a valid identifier)
Why?


Can't start with "to". It's reserved for things like tolower, toupper,
etc...


Tom, you might want to think twice before giving an "obvious" answer when
one respected clc regular is questioning another respected clc regular.
IMHO, such threads and sub-threads must be marked clearly in bold red type:
"Here be dragons" :-)

-nrk.
Technically it's not "buggy C" just not portable. Just like using "errno"
for a local variable isn't a great idea neither.

Tom


--
Remove devnull for email
Nov 14 '05 #9

"nrk" <ra*********@devnull.verizon.net> wrote in message
news:6r****************@nwrddc02.gnilink.net...
Tom St Denis wrote:

"Peter Pichler" <pi*****@pobox.sk> wrote in message
news:40**********@mk-nntp-2.news.uk.tiscali.com...
"Morris Dovey" <mr*****@iedu.com> wrote:

<snippage>

> (BTW toString is not a valid identifier)

Why?
Can't start with "to". It's reserved for things like tolower, toupper,
etc...


Tom, you might want to think twice before giving an "obvious" answer when
one respected clc regular is questioning another respected clc regular.
IMHO, such threads and sub-threads must be marked clearly in bold red

type: "Here be dragons" :-)


True dat. I'll bow out of this conversation. Though I'll add my two cents.
Generally it isn't a good idea to start functions without a descriptive
name. e.g. mp_*() for multiple precision math, etc...

Tom
Nov 14 '05 #10
"nrk" <ra*********@devnull.verizon.net> wrote:
Tom St Denis wrote:
"Peter Pichler" <pi*****@pobox.sk> wrote in message
news:40**********@mk-nntp-2.news.uk.tiscali.com...
"Morris Dovey" <mr*****@iedu.com> wrote:

<snippage>

> (BTW toString is not a valid identifier)

Why?


Can't start with "to". It's reserved for things like tolower, toupper,
etc...


Tom, you might want to think twice before giving an "obvious" answer when
one respected clc regular is questioning another respected clc regular.


*blush*

When did I become a respected clc regular? I thought that one needs to be
marked as an "obvious troll" by ERT first... ;-)

Peter
Nov 14 '05 #11
On Sun, 08 Feb 2004 09:03:39 -0600, Morris Dovey <mr*****@iedu.com>
wrote in comp.lang.c:
Earth wrote:
#include <stdio.h>
char* toString(double d)
{
char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}

main()
{
printf("%s\n", toString(1.234));
}


What do you suppose happens to buffer[9] when you return from
toString()?

(BTW toString is not a valid identifier)


Actually toString is a valid identifier. The standard says:

"7.26.2 Character handling <ctype.h>
1 Function names that begin with either is or to, and a lowercase
letter may be added to the declarations in the <ctype.h> header."

Identifiers beginning with "is" or "to" followed by an underscore,
digit, or uppercase letter do not violate the reserved name space.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #12
Earth wrote:
....
I have written a testing program to try the sprintf fuction and expect
the output is 1.234. However, the output shows nothing. .... #include <stdio.h>
char* toString(double d)
{
char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}

main()
{
printf("%s\n", toString(1.234));
}


But this code ...

#include <stdio.h>
char *toString(double d)
{
static char buffer[9];
sprintf(buffer, "%lf", d);
return buffer;
}

int main(void)
{
printf("%s\n", toString(1.234));
return 0;
}

Has this output:
1.234000

Notice the difference?

--
Martin Ambuhl
Nov 14 '05 #13
Peter Pichler wrote:
"Morris Dovey" <mr*****@iedu.com> wrote:

<snippage>
(BTW toString is not a valid identifier)

Why?


It is a valid identifier. But 'tostring' (with external linkage),
beginning with 'to' followed by a lowercase letter would be a name reserved
to the implementation no matter what headers are included.
--
Martin Ambuhl
Nov 14 '05 #14
"Jack Klein" <ja*******@spamcop.net> wrote in message
news:sk********************************@4ax.com...
On 8 Feb 2004 16:21:07 -0800, ai***@acay.com.au (Peter Nilsson) wrote
in comp.lang.c:
Jack Klein <ja*******@spamcop.net> wrote in message
news:<mn********************************@4ax.com>. ..
On Sun, 08 Feb 2004 09:03:39 -0600, Morris Dovey <mr*****@iedu.com>
wrote in comp.lang.c:

> Earth wrote:
>
> > #include <stdio.h>
> > char* toString(double d)
> > {
> > char buffer[9];
> > sprintf(buffer, "%lf", d);
> > return buffer;
> > }
> >
> > main()
> > {
> > printf("%s\n", toString(1.234));
> > }
>
> (BTW toString is not a valid identifier)

Actually toString is a valid identifier. The standard says:

"7.26.2 Character handling <ctype.h>
1 Function names that begin with either is or to, and a lowercase
letter may be added to the declarations in the <ctype.h> header."

Identifiers beginning with "is" or "to" followed by an underscore,
digit, or uppercase letter do not violate the reserved name space.


Although, case insensitivity of external identifiers is implementation
defined in C90. [This was deprecated and indeed removed in C99.]


Immaterial, the patterns that are and are not reserved by this clause
were identical in C90...


C90 _implicitly_ reserves a broader range of external identifiers for
implementations which do not have case sensitive external linkage.

I don't have C90 itself (only a draft), but I have seen numerous posts
quoting ANSI 4.1.2.1

All identifiers with external linkage in any of the following sections
(including the future library directions) are always reserved for use
as identifiers with external linkage.

So, if tostri* is reserved as an external identifier in C90 (as it is), then
using toStri* as an external identifier will preclude strict conformance.
It's undefined behaviour on machines with case insensitive external
linkage.[*]

If 'Earth' had declared toString static, there wouldn't be a problem.
[*] I don't know of any conforming implementations having this _feature_
exist, but nonetheless, C90 allows for them.

--
Peter
Nov 14 '05 #15
"Peter Pichler" <pi*****@pobox.sk> wrote:
"nrk" <ra*********@devnull.verizon.net> wrote:

<snip>
Tom, you might want to think twice before giving an "obvious" answer when
one respected clc regular is questioning another respected clc regular.


*blush*

When did I become a respected clc regular? I thought that one needs to be
marked as an "obvious troll" by ERT first... ;-)


That seems to be a necessary, albeit not sufficient, prerequisite
when applying for regular status in c.l.c. ;-)

Regards
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
acllc-c++ faq : http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Yodai | last post by:
Hi all.... I have a little problem that's driving me nuts. I can't seem to make any sense of it. I have this small webserver that substitutes some data from a page when finds a substitution...
32
by: Michele | last post by:
I have a code line like this: sprintf(buf, "%20g",*(liftPtr++)) what does it mean? And what does the function sprintf do? Thanks michele
3
by: portergrouptx | last post by:
I am trying to pad a string with leading character zeros. There seems to be a difference between the behavior of sprintf on Windows (Microsoft Visual C++ .NET) and on MVS. Can anyone explain the...
1
by: jimjim | last post by:
Hello, I was wondering about the implications of giving as an argument to sprintf a different data type from the one specified in the format argument. This type of question along with some...
4
by: ypjofficial | last post by:
Hello All, To use sprintf function we have to first create a char * and assign some memory to it or we have to fixed memory sized array. eg. char str;//or it can be //char * str =(char...
12
by: babak | last post by:
Hi everyone I want to format a string (using sprintf) and put it in a messagebox but however I try to do it, it doesn't seem to work. Here is an example sample of what i try to do: char msg;...
6
by: merrittr | last post by:
I am trying to build variables for a function using sprintf. However they don't seem to be proper char strings since submiting literals seems to work fine. Any advice to get me rolling? ...
15
by: krister | last post by:
Hello, I'm working in a quite large system that has some limitations. One of those is that I can't use printf() to get an output on a screen. I'm forced to use a special function, let's call it...
173
by: Ron Ford | last post by:
I'm looking for a freeware c99 compiler for windows. I had intended to use MS's Visual C++ Express and use its C capability. In the past with my MS products, I've simply needed to make .c the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.