C Style Strings

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

    C Style Strings

    Hi,

    I've always used std::string but I'm having to use a 3rd party library
    that returns const char*s. Given:

    char* pString1 = "Blah ";
    const char* pString2 = "Blah Blah";

    How do I append the contents of pString2 to pString? (giving "Blah
    Blah Blah")

    I looked at strcat but that crashes with an unhandled exception.

    Thanks
  • jpalecek@web.de

    #2
    Re: C Style Strings


    scroopy wrote:[color=blue]
    > Hi,
    >
    > I've always used std::string but I'm having to use a 3rd party library
    > that returns const char*s. Given:
    >
    > char* pString1 = "Blah ";
    > const char* pString2 = "Blah Blah";
    >
    > How do I append the contents of pString2 to pString? (giving "Blah
    > Blah Blah")
    >
    > I looked at strcat but that crashes with an unhandled exception.[/color]

    That's easy, do it the C way:

    char* result=new char[strlen(s1)+strl en(s2)+1];
    strcpy(result,s 1);
    strcat(result,s 2);

    Regards
    Jiri Palecek

    Comment

    • Kai-Uwe Bux

      #3
      Re: C Style Strings

      scroopy wrote:
      [color=blue]
      > Hi,
      >
      > I've always used std::string but I'm having to use a 3rd party library
      > that returns const char*s. Given:
      >
      > char* pString1 = "Blah ";
      > const char* pString2 = "Blah Blah";
      >
      > How do I append the contents of pString2 to pString? (giving "Blah
      > Blah Blah")[/color]

      a) Keep using std::string for your own stuff. The std::string class has
      methods that allow you to interact with C-style string interfaces of
      libraries.

      b) Note that in your example above, pString1 is initialized to a const
      string. Any attempt to modify that string would be undefined behavior. The
      danger lies in not declaring pString1 as a char const *.

      c) You could do:

      #include <string>
      #include <algorithm>

      char * strdup ( std::string str ) {
      char * result = new char [ str.length() +1 ];
      std::copy( str.begin(), str.end(), result );
      result[ str.length() ] = 0;
      return ( result );
      }

      int main ( void ) {
      char * pString1 = "Blah ";
      char const * pString2 = "Blah Blah";
      pString1 = strdup( std::string( pString1 ).append( pString2 ) );
      }


      However, I would prefer to use std::string for my own stuff:

      #include <string>

      int main ( void ) {
      std::string pString1 = "Blah "; // rhs returned by some library
      std::string pString2 = "Blah Blah"; // rhs returned by some library
      pString1.append ( pString2 );
      }


      Best

      Kai-Uwe Bux

      Comment

      • Roland Pibinger

        #4
        Re: C Style Strings

        On Thu, 01 Jun 2006 08:35:36 +0100, scroopy <scroopy@nospam .com>
        wrote:[color=blue]
        >I've always used std::string but I'm having to use a 3rd party library
        >that returns const char*s.[/color]

        First you need to find out if you 'own' the returned string, i.e. if
        you must free (maybe delete) the returned char*. Good C libraries
        usually don't require the user to call free.
        [color=blue]
        >Given:
        >
        >char* pString1 = "Blah ";
        >const char* pString2 = "Blah Blah";
        >
        >How do I append the contents of pString2 to pString? (giving "Blah
        >Blah Blah")[/color]

        You can append a const char* to a std::string:

        string myString = "Blah ";
        const char* s = myLibFunc (...);
        if (s) {
        myString += s; // or myString.append (s);
        }
        // free (s); // if it's a bad lib

        Best wishes,
        Roland Pibinger

        Comment

        • kwikius

          #5
          Re: C Style Strings

          scroopy wrote:[color=blue]
          > Hi,
          >
          > I've always used std::string but I'm having to use a 3rd party library
          > that returns const char*s. Given:
          >
          > char* pString1 = "Blah ";
          > const char* pString2 = "Blah Blah";
          >
          > How do I append the contents of pString2 to pString? (giving "Blah
          > Blah Blah")[/color]

          #include <malloc.h>
          #include <cstring>

          char* concat(const char * str1, const char* str2)
          {
          char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);
          if( result != NULL){
          strcpy(result,s tr1);
          strcat(result, str2);
          }
          return result;
          }

          #include <iostream>
          #include <string>

          char* pString1 = "Blah ";
          const char* pString2 = "Blah Blah";


          int main()
          {
          // C-style
          char* str = concat(pString1 ,pString2);
          if(str != NULL){
          std::cout << str <<'\n';
          free(str);
          }

          // C++ style
          std::string str1=std::strin g(pString1) + pString2;
          std::cout << str1 <<'\n';
          }

          I'm not sure if that is the optimal C method. Its interesting to note
          how much better the C++ version is though!

          regards
          Andy Little

          Comment

          • kwikius

            #6
            Re: C Style Strings

            Roland Pibinger wrote:
            [color=blue]
            > First you need to find out if you 'own' the returned string, i.e. if
            > you must free (maybe delete) the returned char*. Good C libraries
            > usually don't require the user to call free.[/color]

            Out of interest ... What is a good C library resource management
            strategy? ... for example (say) modifying the following example

            char* concat(const char * str1, const char* str2)
            {
            char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);
            if( result != NULL){
            strcpy(result,s tr1);
            strcat(result, str2);
            }
            return result;
            }

            char* pString1 = "Blah ";
            const char* pString2 = "Blah Blah";

            int main()
            {
            char* str = concat(pString1 ,pString2);
            if(str != NULL){
            std::cout << str <<'\n';
            free(str); // How to avoid this in C-style?
            }
            }

            regards
            Andy Little

            Comment

            • Richard Bos

              #7
              Re: C Style Strings

              "kwikius" <andy@servocomm .freeserve.co.u k> wrote:
              [color=blue]
              > scroopy wrote:[color=green]
              > > How do I append the contents of pString2 to pString? (giving "Blah
              > > Blah Blah")[/color]
              >
              > #include <malloc.h>
              > #include <cstring>[/color]

              This is not C...
              [color=blue]
              > char* concat(const char * str1, const char* str2)
              > {
              > char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);[/color]

              ....and this is the wrong way to do this in C. And, really, also in C++:
              use new.

              So don't cross-post stuff like that. Follow-ups set.

              Richard

              Comment

              • Richard Heathfield

                #8
                Re: C Style Strings

                Richard Bos said:
                [color=blue]
                > "kwikius" <andy@servocomm .freeserve.co.u k> wrote:
                >[color=green]
                >> scroopy wrote:[color=darkred]
                >> > How do I append the contents of pString2 to pString? (giving "Blah
                >> > Blah Blah")[/color]
                >>
                >> #include <malloc.h>
                >> #include <cstring>[/color]
                >
                > This is not C...[/color]

                ....and it's not C++ either, so I'm not sure why you set followups to clc++.

                The entire article, in fact (his, not yours), was a classic example of the
                kind of thing you get in the Hackitt and Scarper school of programming.

                --
                Richard Heathfield
                "Usenet is a strange place" - dmr 29/7/1999

                email: rjh at above domain (but drop the www, obviously)

                Comment

                • kwikius

                  #9
                  Re: C Style Strings

                  Richard Bos wrote:[color=blue]
                  > "kwikius" <andy@servocomm .freeserve.co.u k> wrote:
                  >[color=green]
                  > > scroopy wrote:[color=darkred]
                  > > > How do I append the contents of pString2 to pString? (giving "Blah
                  > > > Blah Blah")[/color]
                  > >
                  > > #include <malloc.h>
                  > > #include <cstring>[/color]
                  >
                  > This is not C...
                  >[color=green]
                  > > char* concat(const char * str1, const char* str2)
                  > > {
                  > > char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);[/color]
                  >
                  > ...and this is the wrong way to do this in C.[/color]

                  Out of interest what is the right way? BTW... It would seem to me to
                  make sense to cross-post this to comp.lang.c as it is somewhat O.T. for
                  C++. I think It makes sense in terms of a language comparison though,
                  don't you think?
                  [color=blue]
                  > And, really, also in C++:[/color]

                  hmmm... Touchy arent we? I showed a C++ way in my previous post.
                  [color=blue]
                  > use new.[/color]

                  Sure? .. The best way is not to allocate resources the users has to
                  manage , isnt it?.
                  [color=blue]
                  > So don't cross-post stuff like that. Follow-ups set.[/color]

                  Hmm... Are you sure I wouldnt get a better answer to the how to do it
                  in C question in a C newsgroup?

                  regards
                  Andy Little

                  Comment

                  • kwikius

                    #10
                    Re: C Style Strings

                    Richard Heathfield wrote:[color=blue]
                    > Richard Bos said:
                    >[color=green]
                    > > "kwikius" wrote:
                    > >[color=darkred]
                    > >> scroopy wrote:
                    > >> > How do I append the contents of pString2 to pString? (giving "Blah
                    > >> > Blah Blah")
                    > >>
                    > >> #include <malloc.h>
                    > >> #include <cstring>[/color]
                    > >
                    > > This is not C...[/color]
                    >
                    > ...and it's not C++ either, so I'm not sure why you set followups to clc++.
                    >
                    > The entire article, in fact (his, not yours), was a classic example of the
                    > kind of thing you get in the Hackitt and Scarper school of programming.[/color]

                    Thats great! Thanks! Its always good to get positive feedback!

                    regards
                    Andy Little

                    Comment

                    • Roland Pibinger

                      #11
                      Re: C Style Strings

                      On 1 Jun 2006 01:29:33 -0700, "kwikius"
                      <andy@servocomm .freeserve.co.u k> wrote:[color=blue]
                      >Roland Pibinger wrote:
                      >[color=green]
                      >> First you need to find out if you 'own' the returned string, i.e. if
                      >> you must free (maybe delete) the returned char*. Good C libraries
                      >> usually don't require the user to call free.[/color]
                      >
                      >Out of interest ... What is a good C library resource management
                      >strategy? ... for example (say) modifying the following example
                      >
                      >char* concat(const char * str1, const char* str2)[/color]

                      This is almost the declaration of strcat, but strcat operates on the
                      given buffer and doesn't allocate anything. AFAIK, no Standard C
                      library functions returns anything to be freed.
                      Your example could be rewritten as:

                      char* concat (const char * str1, const char* str2, char* result,
                      size_t resultLen);

                      The function returns NULL when the 'contract' (string concatenation)
                      cannot be fulfilled, e.g. because the result-buffer is to small.
                      resultLen is for additional safety.

                      Best wishes,
                      Roland Pibinger

                      Comment

                      • kwikius

                        #12
                        Re: C Style Strings

                        Roland Pibinger wrote:[color=blue]
                        > On 1 Jun 2006 01:29:33 -0700, "kwikius"
                        > <andy@servocomm .freeserve.co.u k> wrote:[/color]

                        [...]
                        [color=blue][color=green]
                        > >Out of interest ... What is a good C library resource management
                        > >strategy? ... for example (say) modifying the following example
                        > >
                        > >char* concat(const char * str1, const char* str2)[/color]
                        >
                        > This is almost the declaration of strcat, but strcat operates on the
                        > given buffer and doesn't allocate anything. AFAIK, no Standard C
                        > library functions returns anything to be freed.
                        > Your example could be rewritten as:
                        >
                        > char* concat (const char * str1, const char* str2, char* result,
                        > size_t resultLen);
                        >
                        > The function returns NULL when the 'contract' (string concatenation)
                        > cannot be fulfilled, e.g. because the result-buffer is to small.
                        > resultLen is for additional safety.[/color]

                        Thanks for the answer. So the answer to the question of a library
                        resource management strategy in C is that there isnt one. Everything to
                        do with resource managment should be done manually by the user, whereas
                        in C++ it is usual to automate resource management thus dramatically
                        simplifying life for the user. That would seem to be a clear win for
                        C++ over C!

                        regards
                        Andy Little

                        Comment

                        • Ian Collins

                          #13
                          Re: C Style Strings

                          kwikius wrote:[color=blue]
                          > Richard Bos wrote:
                          >[color=green]
                          >>"kwikius" <andy@servocomm .freeserve.co.u k> wrote:
                          >>
                          >>[color=darkred]
                          >>>scroopy wrote:
                          >>>
                          >>>>How do I append the contents of pString2 to pString? (giving "Blah
                          >>>>Blah Blah")
                          >>>
                          >>>#include <malloc.h>
                          >>>#include <cstring>[/color]
                          >>
                          >>This is not C...
                          >>
                          >>[color=darkred]
                          >>>char* concat(const char * str1, const char* str2)
                          >>>{
                          >>> char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);[/color]
                          >>
                          >>...and this is the wrong way to do this in C.[/color]
                          >
                          >
                          > Out of interest what is the right way? BTW...[/color]

                          He was probably referring to the cast, which isn't used in C due to
                          implicit conversion from void*

                          --
                          Ian Collins.

                          Comment

                          • Roland Pibinger

                            #14
                            Re: C Style Strings

                            On 1 Jun 2006 02:20:01 -0700, "kwikius"
                            <andy@servocomm .freeserve.co.u k> wrote:[color=blue]
                            >So the answer to the question of a library
                            >resource management strategy in C is that there isnt one.[/color]

                            Let the user provide the necessary resources. Actually, IMO, that's a
                            very good resource management strategy. In C and C++.
                            [color=blue]
                            >Everything to
                            >do with resource managment should be done manually by the user, whereas
                            >in C++ it is usual to automate resource management thus dramatically
                            >simplifying life for the user. That would seem to be a clear win for
                            >C++ over C![/color]

                            Yes, the C++ advantage stems from RAII.

                            Best wishes,
                            Roland Pibinger

                            Comment

                            • Roland Pibinger

                              #15
                              Re: C Style Strings

                              On 1 Jun 2006 01:57:05 -0700, "kwikius"
                              <andy@servocomm .freeserve.co.u k> wrote:[color=blue]
                              >Richard Heathfield wrote:[color=green]
                              >> The entire article, in fact (his, not yours), was a classic example of the
                              >> kind of thing you get in the Hackitt and Scarper school of programming.[/color]
                              >
                              >Thats great! Thanks! Its always good to get positive feedback![/color]

                              BTW, an interesting C-string library can be found here:


                              Best wishes,
                              Roland Pibinger

                              Comment

                              Working...