Integer to string conversion

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

    Integer to string conversion

    Hello friends:

    I know some people here don't like to answer C++ questions, but I
    believe this is really about the underlying C code. Anyway I have posted
    as well to the other group someone suggested ("comp.lang.c++ ") just in
    case.

    I think the problem is that in my C++ class, we were taught to use cin,
    cout etc. but now I need to use the primitive C operations printf etc.
    and I don't understand exactly how they work.

    I'm trying to convert an integer into a string. Here's what I'm trying,
    but when I try to output the string returned from the function, I just
    get garbage. How should I be using sprintf?

    Thanks.



    char *App::IntToStri ng(int i) //doesn't really rely on classes
    {
    char buf[2];
    char *out = buf;
    sprintf(out, "%d", i);
    return out;
    }
  • Ian Collins

    #2
    Re: Integer to string conversion

    pradeep wrote:
    Hello friends:
    >
    I know some people here don't like to answer C++ questions, but I
    believe this is really about the underlying C code. Anyway I have posted
    as well to the other group someone suggested ("comp.lang.c++ ") just in
    case.
    >
    I think the problem is that in my C++ class, we were taught to use cin,
    cout etc. but now I need to use the primitive C operations printf etc.
    and I don't understand exactly how they work.
    >
    Why? If you are writing C++, use C++ idioms.

    f'ups set.

    --
    Ian Collins.

    Comment

    • Default User

      #3
      Re: Integer to string conversion

      pradeep wrote:
      I'm trying to convert an integer into a string. Here's what I'm
      trying, but when I try to output the string returned from the
      function, I just get garbage. How should I be using sprintf?
      char *App::IntToStri ng(int i) //doesn't really rely on classes
      {
      char buf[2];
      char *out = buf;
      sprintf(out, "%d", i);
      return out;
      }
      Your problem is that you are returning a pointer to local storage. That
      is invalid as soon as the function returns. In C, you would either pass
      in a pointer to storage, or dynamically allocate some for return.

      In C++, you shouldn't do this at all. Ask in comp.lang.c++ for ways to
      do it.




      Brian

      Comment

      • peter koch

        #4
        Re: Integer to string conversion

        On 28 Apr., 23:38, pradeep <nos...@nospam. comwrote:
        Hello friends:
        >
        I know some people here don't like to answer C++ questions, but I
        believe this is really about the underlying C code. Anyway I have posted
          as well to the other group someone suggested ("comp.lang.c++ ") just in
        case.
        We do like answering C++ questions, so it is more the other way
        around: C functions are better asked in comp.lang.c - even if they
        also (as in your case) happen to be C++ functions.
        >
        I think the problem is that in my C++ class, we were taught to use cin,
        cout etc. but now I need to use the primitive C operations printf etc.
        Why?
        and I don't understand exactly how they work.
        You need to study first!
        >
        I'm trying to convert an integer into a string. Here's what I'm trying,
        but when I try to output the string returned from the function, I just
        get garbage. How should I be using sprintf?
        >
        Thanks.
        >
        char *App::IntToStri ng(int i) //doesn't really rely on classes
        Why a pointer to a character? I'd presume a std::string would be more
        appropriate.
        {
             char buf[2];
        Why only two characters? This definitely is wrong.
             char *out = buf;
             sprintf(out, "%d", i);
        Why %d? So far as I remember (I haven't used printf-type formatting
        for a very long time), the correct format is %i.
        Also I believe there is a snprintf available that gives safer code.
             return out;
        Here you return a pointer to a temporary variable. This is never a
        good idea.
        }
        Finding the answer to the questions above hopefully will help your
        progress!

        /Peter

        Comment

        • Bartc

          #5
          Re: Integer to string conversion


          "pradeep" <nospam@nospam. comwrote in message news:fv5g52$rul $1@aioe.org...
          Hello friends:
          >
          I know some people here don't like to answer C++ questions, but I believe
          this is really about the underlying C code. Anyway I have posted as well
          to the other group someone suggested ("comp.lang.c++ ") just in case.
          >
          I think the problem is that in my C++ class, we were taught to use cin,
          cout etc. but now I need to use the primitive C operations printf etc. and
          I don't understand exactly how they work.
          >
          I'm trying to convert an integer into a string. Here's what I'm trying,
          but when I try to output the string returned from the function, I just get
          garbage. How should I be using sprintf?
          >
          Thanks.
          >
          >
          >
          char *App::IntToStri ng(int i) //doesn't really rely on classes
          {
          char buf[2];
          char *out = buf;
          sprintf(out, "%d", i);
          return out;
          }
          If this was C (you'd have to get rid of that :: for a start):

          The buffer of 2 characters is far too small; what if i is <0 or >9? Make it
          a much more reasonable width, remembering it needs a zero terminator too.

          Also the buf[2] being in automatic storage, will disappear when you return
          from the function.

          You can try making buf static. And bigger.

          --
          Bartc



          Comment

          • Jim Langston

            #6
            Re: Integer to string conversion

            pradeep wrote:
            Hello friends:
            >
            I know some people here don't like to answer C++ questions, but I
            believe this is really about the underlying C code. Anyway I have
            posted as well to the other group someone suggested
            ("comp.lang.c++ ") just in case.
            >
            I think the problem is that in my C++ class, we were taught to use
            cin, cout etc. but now I need to use the primitive C operations
            printf etc. and I don't understand exactly how they work.
            >
            I'm trying to convert an integer into a string. Here's what I'm
            trying, but when I try to output the string returned from the
            function, I just get garbage. How should I be using sprintf?
            >
            Thanks.
            >
            >
            >
            char *App::IntToStri ng(int i) //doesn't really rely on classes
            {
            char buf[2];
            Not big enough by far and disappears once IntToString finishes.
            char *out = buf;
            No reason to have to do this.
            sprintf(out, "%d", i);
            sprintf( buf, "%d", i );
            would also work, although there are hte other problems.
            return out;
            you are returning a pointer to a buffer that goes out of scope when the
            function returns.
            }
            So, how to fix this? Simplest is to make the buffer static so it doesn't
            disappear when the function returns and make it big enough. char buf[2];
            is only large enough to hold "0" through "9". An integer can hold quite a
            larger value, however. 10 or 11 digits I think.

            char *App::IntToStri ng(int i) //doesn't really rely on classes
            {
            static char buf[12];
            sprintf(buf, "%d", i);
            return buf;
            }

            Shoudl fix the immediate errors, but does not fix any design issues. Such
            as the fact if you called this twice in a row, both returned char*'s would
            point to the same value. I.E.

            char* Value1;
            char* Value2;

            Value1 = IntToString( 10 );
            Value2 = IntToString( 11 );

            std::cout << Value1 << " " << Value2;

            would output 11 11 since the pointers returned by IntToString are identical,
            and the static buffer was changed.

            It is better to return a std::string. You can do the conversion either as is
            and convert to a std::string, or use use std::stringstre am. (Untested
            code).

            std::string App::IntToStrin g( int i )
            {
            std::stringstre am Convert;
            Convert << i;
            std::string Answer;
            Convert >Answer;

            return Convert.string( );
            }

            Personally, I use a template for this.

            template<typena me T, typename F T StrmConvert( const F from )
            {
            std::stringstre am temp;
            temp << from;
            T to = T();
            temp >to;
            return to;
            }

            template<typena me Fstd::string StrmConvert( const F from )
            {
            return StrmConvert<std ::string>( from );
            }

            So I can do:

            std::string Value = StrmConvert( 10 );

            or even:

            int Value = StrmConvert<int >( "10" );

            Note that my StrmConvert does not have any error checking, any errors would
            simply return a default constructed value. I.E. If you tried to convert
            "xyz" to an int the result would be 0.
            --
            Jim Langston
            tazmaster@rocke tmail.com


            Comment

            • yang cheng

              #7
              Re: Integer to string conversion

              buf is a local variable, you should not try to return a pointer of it.

              On Apr 28, 5:38 pm, pradeep <nos...@nospam. comwrote:
              Hello friends:
              >
              I know some people here don't like to answer C++ questions, but I
              believe this is really about the underlying C code. Anyway I have posted
              as well to the other group someone suggested ("comp.lang.c++ ") just in
              case.
              >
              I think the problem is that in my C++ class, we were taught to use cin,
              cout etc. but now I need to use the primitive C operations printf etc.
              and I don't understand exactly how they work.
              >
              I'm trying to convert an integer into a string. Here's what I'm trying,
              but when I try to output the string returned from the function, I just
              get garbage. How should I be using sprintf?
              >
              Thanks.
              >
              char *App::IntToStri ng(int i) //doesn't really rely on classes
              {
              char buf[2];
              char *out = buf;
              sprintf(out, "%d", i);
              return out;
              >
              }

              Comment

              • ppi

                #8
                Re: Integer to string conversion

                char *App::IntToStri ng(int i) //doesn't really rely on classes
                {
                char buf[2];
                char *out = buf;
                sprintf(out, "%d", i);
                return out;
                >
                }
                you are using a local char array. When returning from the function, it
                has been recycled (memory released) - hence the garbage.
                provide the array to store the conversion in the parameters list or
                return a c++ string.

                -- paulo

                Comment

                • Juha Nieminen

                  #9
                  Re: Integer to string conversion

                  pradeep wrote:
                  I think the problem is that in my C++ class, we were taught to use cin,
                  cout etc. but now I need to use the primitive C operations printf etc.
                  and I don't understand exactly how they work.
                  >
                  I'm trying to convert an integer into a string.
                  You don't need printf for that. You can do it like this:

                  std::ostringstr eam os;
                  os << i;
                  std::string theString = os.str();

                  Comment

                  • Keith Thompson

                    #10
                    Re: Integer to string conversion

                    pradeep <nospam@nospam. comwrites:
                    I know some people here don't like to answer C++ questions, but I
                    believe this is really about the underlying C code. Anyway I have
                    posted as well to the other group someone suggested ("comp.lang.c++ ")
                    just in case.
                    >
                    I think the problem is that in my C++ class, we were taught to use
                    cin, cout etc. but now I need to use the primitive C operations printf
                    etc. and I don't understand exactly how they work.
                    >
                    I'm trying to convert an integer into a string. Here's what I'm
                    trying, but when I try to output the string returned from the
                    function, I just get garbage. How should I be using sprintf?
                    [...]
                    >
                    char *App::IntToStri ng(int i) //doesn't really rely on classes
                    {
                    char buf[2];
                    char *out = buf;
                    sprintf(out, "%d", i);
                    return out;
                    }
                    You could (and should) have avoided any possible controversy by (a)
                    dropping the "::" from your function's name, (b) dropping any mention
                    of C++ and classes, and (c) not cross-posting to comp.lang.c++. You
                    would then have been asking an appropriate C question in a C newsgroup
                    (to which I've redirected followups).

                    As far as C is concerned, the FAQ is at <http://www.c-faq.com/>, and
                    you've asked question 7.5a. Read the answer there, and follow the
                    references to other questions. If that doesn't tell you what you need
                    to know, post a followup to comp.lang.c only.

                    Or, if you just wanted to use sprintf in C++ code for some reason, you
                    could have just posted to comp.lang.c++. They'd undoubtedly ask you
                    why you don't just use the usual C++ idioms -- which is a very good
                    question, and one you might consider answering in a followup to
                    comp.lang.c++ only.

                    --
                    Keith Thompson (The_Other_Keit h) <kst-u@mib.org>
                    Nokia
                    "We must do something. This is something. Therefore, we must do this."
                    -- Antony Jay and Jonathan Lynn, "Yes Minister"

                    Comment

                    • Keith Thompson

                      #11
                      Re: Integer to string conversion

                      peter koch <peter.koch.lar sen@gmail.comwr ites:
                      On 28 Apr., 23:38, pradeep <nos...@nospam. comwrote:
                      [...]
                      >     sprintf(out, "%d", i);
                      Why %d? So far as I remember (I haven't used printf-type formatting
                      for a very long time), the correct format is %i.
                      You misremember. For printf, "%d" and "%i" are equivalent. (It's 'd'
                      for decimal, 'i' for integer).
                      Also I believe there is a snprintf available that gives safer code.
                      Yes, but it's a new feature in C99. It's likely to be available as an
                      extension in pre-C99 C implementations , or in C++ implementations , but
                      it's not guaranteed to be there. (But if you're programming in C++
                      I'm not sure why you'd use either sprintf or snprintf.)

                      --
                      Keith Thompson (The_Other_Keit h) <kst-u@mib.org>
                      Nokia
                      "We must do something. This is something. Therefore, we must do this."
                      -- Antony Jay and Jonathan Lynn, "Yes Minister"

                      Comment

                      • Jack Klein

                        #12
                        Re: Integer to string conversion

                        On Mon, 28 Apr 2008 15:11:34 -0700 (PDT), peter koch
                        <peter.koch.lar sen@gmail.comwr ote in comp.lang.c:
                        On 28 Apr., 23:38, pradeep <nos...@nospam. comwrote:
                        Hello friends:

                        I know some people here don't like to answer C++ questions, but I
                        believe this is really about the underlying C code. Anyway I have posted
                          as well to the other group someone suggested ("comp.lang.c++ ") just in
                        case.
                        We do like answering C++ questions, so it is more the other way
                        around: C functions are better asked in comp.lang.c - even if they
                        also (as in your case) happen to be C++ functions.
                        <off-topic>

                        You're completely wrong about that. Nothing at all in the C standard
                        states that there is a function named printf() in the C++ language.
                        Nothing at all in the C standard states that, if there is a function
                        named printf() in the C++ language, that it works the same as, or
                        differently than the one that the C standard does define in the C
                        library.

                        In actual fact, the C++ standard does change the definition of some C
                        functions to some extent. Not many, but some. And there is the fact
                        that std::printf() is not something that exists in C at all.

                        Regardless, the decision of the C++ committee to inherit much from C
                        does not impose any burden on the C standard, or a C language group,
                        to support those functions in a program in C++, C#, Objective C, Java,
                        Javascript, D, or any other language that happens to decide to base
                        itself on C.

                        Questions about the use of C library functions "inherited" by C++ in a
                        C++ program are not about C and do not belong here.

                        The fact that some posters in comp.lang.c++ like to browbeat anyone
                        using a function that C++ "inherited" from C when there is any
                        possible newer C++ alternative, no matter how much more complicated,
                        does not make anything at all in a C++ program topical here.

                        </off-topic>

                        --
                        Jack Klein
                        Home: http://JK-Technology.Com
                        FAQs for
                        comp.lang.c http://c-faq.com/
                        comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                        alt.comp.lang.l earn.c-c++

                        Comment

                        • Jack Klein

                          #13
                          Re: Integer to string conversion

                          On Mon, 28 Apr 2008 15:21:35 -0700, "Jim Langston"
                          <tazmaster@rock etmail.comwrote in comp.lang.c:

                          Personally, I use a template for this.
                          Kindly don't use templates in comp.lang.c.
                          template<typena me T, typename F T StrmConvert( const F from )
                          clc.c(1) : error C2143: syntax error : missing '{' before '<'
                          clc.c(1) : error C2059: syntax error : '<'

                          Nope, that won't work in the programs discussed here.

                          Please don't vandalize comp.lang.c with C++ discussions.

                          --
                          Jack Klein
                          Home: http://JK-Technology.Com
                          FAQs for
                          comp.lang.c http://c-faq.com/
                          comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                          alt.comp.lang.l earn.c-c++

                          Comment

                          • pradeep

                            #14
                            Re: Integer to string conversion

                            Thanks for all the answers.

                            I think Jim probably has the best solution but we haven't covered
                            templates yet and they seem very confusing, the code just blurs in front
                            of my eyes!

                            What I'd like is a simpler version of this. Here's an idea I had which I
                            think is very similar to what Jim tries to do but easier: make a pipe
                            and then cout>the integer to the pipe, but then cin<< it back as a
                            string. Would that work?

                            There is a pipe command on my computer but it isn't mentioned in the
                            text book. I don't understand the argument, it's an array of 2 int. I
                            tried passing NULL but it didn't work.

                            Thanks.


                            Jim Langston wrote:
                            pradeep wrote:
                            >
                            >>Hello friends:
                            >>
                            >>I know some people here don't like to answer C++ questions, but I
                            >>believe this is really about the underlying C code. Anyway I have
                            >posted as well to the other group someone suggested
                            >>("comp.lang.c ++") just in case.
                            >>
                            >>I think the problem is that in my C++ class, we were taught to use
                            >>cin, cout etc. but now I need to use the primitive C operations
                            >>printf etc. and I don't understand exactly how they work.
                            >>
                            >>I'm trying to convert an integer into a string. Here's what I'm
                            >>trying, but when I try to output the string returned from the
                            >>function, I just get garbage. How should I be using sprintf?
                            >>
                            >>Thanks.
                            >>
                            >>
                            >>
                            >>char *App::IntToStri ng(int i) //doesn't really rely on classes
                            >>{
                            > char buf[2];
                            >
                            >
                            Not big enough by far and disappears once IntToString finishes.
                            >
                            >
                            > char *out = buf;
                            >
                            >
                            No reason to have to do this.
                            >
                            >
                            > sprintf(out, "%d", i);
                            >
                            >
                            sprintf( buf, "%d", i );
                            would also work, although there are hte other problems.
                            >
                            >
                            > return out;
                            >
                            >
                            you are returning a pointer to a buffer that goes out of scope when the
                            function returns.
                            >
                            >
                            >>}
                            >
                            >
                            So, how to fix this? Simplest is to make the buffer static so it doesn't
                            disappear when the function returns and make it big enough. char buf[2];
                            is only large enough to hold "0" through "9". An integer can hold quite a
                            larger value, however. 10 or 11 digits I think.
                            >
                            char *App::IntToStri ng(int i) //doesn't really rely on classes
                            {
                            static char buf[12];
                            sprintf(buf, "%d", i);
                            return buf;
                            }
                            >
                            Shoudl fix the immediate errors, but does not fix any design issues. Such
                            as the fact if you called this twice in a row, both returned char*'s would
                            point to the same value. I.E.
                            >
                            char* Value1;
                            char* Value2;
                            >
                            Value1 = IntToString( 10 );
                            Value2 = IntToString( 11 );
                            >
                            std::cout << Value1 << " " << Value2;
                            >
                            would output 11 11 since the pointers returned by IntToString are identical,
                            and the static buffer was changed.
                            >
                            It is better to return a std::string. You can do the conversion either as is
                            and convert to a std::string, or use use std::stringstre am. (Untested
                            code).
                            >
                            std::string App::IntToStrin g( int i )
                            {
                            std::stringstre am Convert;
                            Convert << i;
                            std::string Answer;
                            Convert >Answer;
                            >
                            return Convert.string( );
                            }
                            >
                            Personally, I use a template for this.
                            >
                            template<typena me T, typename F T StrmConvert( const F from )
                            {
                            std::stringstre am temp;
                            temp << from;
                            T to = T();
                            temp >to;
                            return to;
                            }
                            >
                            template<typena me Fstd::string StrmConvert( const F from )
                            {
                            return StrmConvert<std ::string>( from );
                            }
                            >
                            So I can do:
                            >
                            std::string Value = StrmConvert( 10 );
                            >
                            or even:
                            >
                            int Value = StrmConvert<int >( "10" );
                            >
                            Note that my StrmConvert does not have any error checking, any errors would
                            simply return a default constructed value. I.E. If you tried to convert
                            "xyz" to an int the result would be 0.

                            Comment

                            • Jim Langston

                              #15
                              Re: Integer to string conversion

                              pradeep wrote:
                              Thanks for all the answers.
                              >
                              I think Jim probably has the best solution but we haven't covered
                              templates yet and they seem very confusing, the code just blurs in
                              front of my eyes!
                              >
                              What I'd like is a simpler version of this. Here's an idea I had
                              which I think is very similar to what Jim tries to do but easier:
                              make a pipe and then cout>the integer to the pipe, but then cin<<
                              it back as a string. Would that work?
                              >
                              There is a pipe command on my computer but it isn't mentioned in the
                              text book. I don't understand the argument, it's an array of 2 int. I
                              tried passing NULL but it didn't work.
                              Yes. That is what the stringstream example I also gave did.

                              std::string App::IntToStrin g( int i )
                              {
                              std::stringstre am Convert;
                              Convert << i;
                              std::string Answer;
                              Convert >Answer;

                              return Convert.string( );
                              }

                              std::stringstre am is in this case the "pipe". Just instead of "cin" and
                              "cout" you use the name of the instantized stringstream. Just make sure you
                              #include <sstream>
                              #include <string>
                              Jim Langston wrote:
                              >pradeep wrote:
                              >>
                              >>Hello friends:
                              >>>
                              >>I know some people here don't like to answer C++ questions, but I
                              >>believe this is really about the underlying C code. Anyway I have
                              >>posted as well to the other group someone suggested
                              >>("comp.lang.c ++") just in case.
                              >>>
                              >>I think the problem is that in my C++ class, we were taught to use
                              >>cin, cout etc. but now I need to use the primitive C operations
                              >>printf etc. and I don't understand exactly how they work.
                              >>>
                              >>I'm trying to convert an integer into a string. Here's what I'm
                              >>trying, but when I try to output the string returned from the
                              >>function, I just get garbage. How should I be using sprintf?
                              >>>
                              >>Thanks.
                              >>>
                              >>>
                              >>>
                              >>char *App::IntToStri ng(int i) //doesn't really rely on classes
                              >>{
                              >> char buf[2];
                              >>
                              >>
                              >Not big enough by far and disappears once IntToString finishes.
                              >>
                              >>
                              >> char *out = buf;
                              >>
                              >>
                              >No reason to have to do this.
                              >>
                              >>
                              >> sprintf(out, "%d", i);
                              >>
                              >>
                              >sprintf( buf, "%d", i );
                              >would also work, although there are hte other problems.
                              >>
                              >>
                              >> return out;
                              >>
                              >>
                              >you are returning a pointer to a buffer that goes out of scope when
                              >the function returns.
                              >>
                              >>
                              >>}
                              >>
                              >>
                              >So, how to fix this? Simplest is to make the buffer static so it
                              >doesn't disappear when the function returns and make it big enough. char
                              >buf[2]; is only large enough to hold "0" through "9". An
                              >integer can hold quite a larger value, however. 10 or 11 digits I
                              >think. char *App::IntToStri ng(int i) //doesn't really rely on classes
                              >{
                              > static char buf[12];
                              > sprintf(buf, "%d", i);
                              > return buf;
                              >}
                              >>
                              >Shoudl fix the immediate errors, but does not fix any design issues.
                              >Such as the fact if you called this twice in a row, both returned
                              >char*'s would point to the same value. I.E.
                              >>
                              >char* Value1;
                              >char* Value2;
                              >>
                              >Value1 = IntToString( 10 );
                              >Value2 = IntToString( 11 );
                              >>
                              >std::cout << Value1 << " " << Value2;
                              >>
                              >would output 11 11 since the pointers returned by IntToString are
                              >identical, and the static buffer was changed.
                              >>
                              >It is better to return a std::string. You can do the conversion
                              >either as is and convert to a std::string, or use use
                              >std::stringstr eam. (Untested code).
                              >>
                              >std::string App::IntToStrin g( int i )
                              >{
                              > std::stringstre am Convert;
                              > Convert << i;
                              > std::string Answer;
                              > Convert >Answer;
                              >>
                              > return Convert.string( );
                              >}
                              >>
                              >Personally, I use a template for this.
                              >>
                              > template<typena me T, typename F T StrmConvert( const F from )
                              > {
                              > std::stringstre am temp;
                              > temp << from;
                              > T to = T();
                              > temp >to;
                              > return to;
                              > }
                              >>
                              > template<typena me Fstd::string StrmConvert( const F from )
                              > {
                              > return StrmConvert<std ::string>( from );
                              > }
                              >>
                              >So I can do:
                              >>
                              >std::string Value = StrmConvert( 10 );
                              >>
                              >or even:
                              >>
                              >int Value = StrmConvert<int >( "10" );
                              >>
                              >Note that my StrmConvert does not have any error checking, any
                              >errors would simply return a default constructed value. I.E. If
                              >you tried to convert "xyz" to an int the result would be 0.


                              --
                              Jim Langston
                              tazmaster@rocke tmail.com


                              Comment

                              Working...