sprintf function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Earth

    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) );
    }
  • Morris Dovey

    #2
    Re: sprintf function

    Earth wrote:
    [color=blue]
    > #include <stdio.h>
    > char* toString(double d)
    > {
    > char buffer[9];
    > sprintf(buffer, "%lf", d);
    > return buffer;
    > }
    >
    > main()
    > {
    > printf("%s\n", toString(1.234) );
    > }[/color]

    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.

    Comment

    • Ian Peattie

      #3
      Re: sprintf function

      In article <ab940065.04020 80651.60d043ee@ posting.google. com>, earth_sw@yahoo. com.hk (Earth) wrote:
      [color=blue]
      >I have written a testing program to try the sprintf fuction and expect
      >the output is 1.234. However, the output shows nothing.[/color]
      [color=blue]
      >#include <stdio.h>
      >char* toString(double d)
      >{
      > char buffer[9];
      > sprintf(buffer, "%lf", d);
      > return buffer;
      >}[/color]

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

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

      Ian.

      Comment

      • nrk

        #4
        Re: sprintf function

        Earth wrote:
        [color=blue]
        > 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) );
        > }[/color]

        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:



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



        -nrk.

        --
        Remove devnull for email

        Comment

        • Peter Pichler

          #5
          Re: sprintf function

          "Morris Dovey" <mrdovey@iedu.c om> wrote:

          <snippage>
          [color=blue]
          > (BTW toString is not a valid identifier)[/color]

          Why?


          Comment

          • Tom St Denis

            #6
            Re: sprintf function


            "Peter Pichler" <pichlo7@pobox. sk> wrote in message
            news:40265cdd$1 _2@mk-nntp-2.news.uk.tisca li.com...[color=blue]
            > "Morris Dovey" <mrdovey@iedu.c om> wrote:
            >
            > <snippage>
            >[color=green]
            > > (BTW toString is not a valid identifier)[/color]
            >
            > Why?[/color]

            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


            Comment

            • Peter Pichler

              #7
              Re: sprintf function

              "Tom St Denis" <tom@securescie nce.net> wrote in message
              news:_7tVb.3392 4$3YE1.27018@ne ws04.bloor.is.n et.cable.rogers .com...[color=blue]
              > "Peter Pichler" <pichlo7@pobox. sk> wrote in message
              > news:40265cdd$1 _2@mk-nntp-2.news.uk.tisca li.com...[color=green]
              > > "Morris Dovey" <mrdovey@iedu.c om> wrote:
              > >
              > > <snippage>
              > >[color=darkred]
              > > > (BTW toString is not a valid identifier)[/color]
              > >
              > > Why?[/color]
              >
              > Can't start with "to".[/color]

              ....and a lowercase letter.
              [color=blue]
              > It's reserved for things like tolower, toupper,
              > etc...[/color]

              But not toString. 'S' is not a lowercase letter, AFAICS.
              [color=blue]
              > Technically it's not "buggy C" just not portable. Just like using "errno"
              > for a local variable isn't a great idea neither.[/color]

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

              Peter


              Comment

              • Eric Amick

                #8
                Re: sprintf function

                On 8 Feb 2004 06:51:20 -0800, earth_sw@yahoo. com.hk (Earth) wrote:
                [color=blue]
                >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;
                >}[/color]

                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

                Comment

                • nrk

                  #9
                  Re: sprintf function

                  Tom St Denis wrote:
                  [color=blue]
                  >
                  > "Peter Pichler" <pichlo7@pobox. sk> wrote in message
                  > news:40265cdd$1 _2@mk-nntp-2.news.uk.tisca li.com...[color=green]
                  >> "Morris Dovey" <mrdovey@iedu.c om> wrote:
                  >>
                  >> <snippage>
                  >>[color=darkred]
                  >> > (BTW toString is not a valid identifier)[/color]
                  >>
                  >> Why?[/color]
                  >
                  > Can't start with "to". It's reserved for things like tolower, toupper,
                  > etc...
                  >[/color]

                  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.
                  [color=blue]
                  > Technically it's not "buggy C" just not portable. Just like using "errno"
                  > for a local variable isn't a great idea neither.
                  >
                  > Tom[/color]

                  --
                  Remove devnull for email

                  Comment

                  • Tom St Denis

                    #10
                    Re: sprintf function


                    "nrk" <ram_nrk2000@de vnull.verizon.n et> wrote in message
                    news:6rtVb.2457 $4e3.114@nwrddc 02.gnilink.net. ..[color=blue]
                    > Tom St Denis wrote:
                    >[color=green]
                    > >
                    > > "Peter Pichler" <pichlo7@pobox. sk> wrote in message
                    > > news:40265cdd$1 _2@mk-nntp-2.news.uk.tisca li.com...[color=darkred]
                    > >> "Morris Dovey" <mrdovey@iedu.c om> wrote:
                    > >>
                    > >> <snippage>
                    > >>
                    > >> > (BTW toString is not a valid identifier)
                    > >>
                    > >> Why?[/color]
                    > >
                    > > Can't start with "to". It's reserved for things like tolower, toupper,
                    > > etc...
                    > >[/color]
                    >
                    > 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[/color]
                    type:[color=blue]
                    > "Here be dragons" :-)[/color]

                    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


                    Comment

                    • Peter Pichler

                      #11
                      Re: sprintf function

                      "nrk" <ram_nrk2000@de vnull.verizon.n et> wrote:[color=blue]
                      > Tom St Denis wrote:[color=green]
                      > > "Peter Pichler" <pichlo7@pobox. sk> wrote in message
                      > > news:40265cdd$1 _2@mk-nntp-2.news.uk.tisca li.com...[color=darkred]
                      > >> "Morris Dovey" <mrdovey@iedu.c om> wrote:
                      > >>
                      > >> <snippage>
                      > >>
                      > >> > (BTW toString is not a valid identifier)
                      > >>
                      > >> Why?[/color]
                      > >
                      > > Can't start with "to". It's reserved for things like tolower, toupper,
                      > > etc...[/color]
                      >
                      > Tom, you might want to think twice before giving an "obvious" answer when
                      > one respected clc regular is questioning another respected clc regular.[/color]

                      *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


                      Comment

                      • Jack Klein

                        #12
                        Re: sprintf function

                        On Sun, 08 Feb 2004 09:03:39 -0600, Morris Dovey <mrdovey@iedu.c om>
                        wrote in comp.lang.c:
                        [color=blue]
                        > Earth wrote:
                        >[color=green]
                        > > #include <stdio.h>
                        > > char* toString(double d)
                        > > {
                        > > char buffer[9];
                        > > sprintf(buffer, "%lf", d);
                        > > return buffer;
                        > > }
                        > >
                        > > main()
                        > > {
                        > > printf("%s\n", toString(1.234) );
                        > > }[/color]
                        >
                        > What do you suppose happens to buffer[9] when you return from
                        > toString()?
                        >
                        > (BTW toString is not a valid identifier)[/color]

                        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.l earn.c-c++

                        Comment

                        • Martin Ambuhl

                          #13
                          Re: sprintf function

                          Earth wrote:
                          ....[color=blue]
                          > I have written a testing program to try the sprintf fuction and expect
                          > the output is 1.234. However, the output shows nothing.[/color]
                          ....[color=blue]
                          > #include <stdio.h>
                          > char* toString(double d)
                          > {
                          > char buffer[9];
                          > sprintf(buffer, "%lf", d);
                          > return buffer;
                          > }
                          >
                          > main()
                          > {
                          > printf("%s\n", toString(1.234) );
                          > }[/color]

                          But this code ...

                          #include <stdio.h>
                          char *toString(doubl e 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

                          Comment

                          • Martin Ambuhl

                            #14
                            Re: sprintf function

                            Peter Pichler wrote:
                            [color=blue]
                            > "Morris Dovey" <mrdovey@iedu.c om> wrote:
                            >
                            > <snippage>
                            >[color=green]
                            >>(BTW toString is not a valid identifier)[/color]
                            >
                            >
                            > Why?[/color]

                            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

                            Comment

                            • Peter Nilsson

                              #15
                              Re: sprintf function

                              "Jack Klein" <jackklein@spam cop.net> wrote in message
                              news:sksd20518j 5rj1smgejc6m4dt 25ov5epvu@4ax.c om...[color=blue]
                              > On 8 Feb 2004 16:21:07 -0800, airia@acay.com. au (Peter Nilsson) wrote
                              > in comp.lang.c:[color=green]
                              > > Jack Klein <jackklein@spam cop.net> wrote in message
                              > > news:<mnsc20h8g 3quu92re8e7cmea jgepknb5ks@4ax. com>...[color=darkred]
                              > > > On Sun, 08 Feb 2004 09:03:39 -0600, Morris Dovey <mrdovey@iedu.c om>
                              > > > 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.[/color]
                              > >
                              > > Although, case insensitivity of external identifiers is implementation
                              > > defined in C90. [This was deprecated and indeed removed in C99.][/color]
                              >
                              > Immaterial, the patterns that are and are not reserved by this clause
                              > were identical in C90...[/color]

                              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


                              Comment

                              Working...