Simple toString() problem

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

    Simple toString() problem

    Hi,

    <code snippet>
    char* Car::toString()
    {
    //Example [XR, Holden]
    char* str = {"[", carID, ",", carName, "]"};
    return str;
    }

    Note: carID and carName are private variables of class Car

    Compile Error: Car.cpp initializer for scalar variable requires one element

    Basically, the toString() method doesn't work. Any help appreciated. Note,
    I'm not interested in working with the newer string data type because I want
    to learnto do it with pointers to char.


    Regards
    wewewe







  • Dimitris Kamenopoulos

    #2
    Re: Simple toString() problem

    Ying Yang wrote:
    [color=blue]
    > Hi,
    >
    > <code snippet>
    > char* Car::toString()
    > {
    > //Example [XR, Holden]
    > char* str = {"[", carID, ",", carName, "]"};[/color]

    The way I see it, you want to return something like:

    "[carId,carName]"

    with the real values of carId and carName, of course. I assume carId and
    carName are also char*.

    Well,
    1) {"[", carID, ",", carName, "]"} is basically the syntax for an array of
    stuff (presumably char* if carId and carName are also char*). In other
    words, if we call it str, its contents are:
    str[0] == "{"
    str[1] == carId
    str[2] == ","
    str[3] == carName
    str[4] == "]"

    Anyway, its type is char*[5] not char*, which is why you are getting the
    error. You are trying to assign an array to a scalar variable.

    2) How you could do it with old-styled stuff:
    //first you would need a buffer:
    char * buf = new char[30]; //let's say a 30 character buffer
    //then fill the buffer
    sprintf(buf,"[%s,%s]", carId, carName); //sprintf requires #include <cstdio>
    return buf;


    Notice that I allocated buf with new, otherwise it would be destroyed as
    soon as toString() exits and the returned pointer would point to nowhere.

    I think you need a good C++ book. See the FAQ.







    Comment

    • Ying Yang

      #3
      Re: Simple toString() problem

      [color=blue][color=green]
      > > Hi,
      > >
      > > <code snippet>
      > > char* Car::toString()
      > > {
      > > //Example [XR, Holden]
      > > char* str = {"[", carID, ",", carName, "]"};
      > > return str;
      > > }
      > >
      > > Note: carID and carName are private variables of class Car[/color]
      >
      > Use an ostringstream, and switch to using std::string for the return[/color]
      value.[color=blue]
      >
      > ostringstream oss;
      > oss << '[' << carID << ',' << carName << ']'; // just like using cout
      > return oss.str();
      >
      > If you /must/ use C-style strings, you're going to have to tackle dynamic
      > memory management. That's a whole 'nother discussion, though.
      >
      > Josh[/color]

      What do i have to include to use ostringstream oss?? doesn't not seem like a
      normal way of doing it with pointers to char.

      wewewe


      Comment

      • Josh Sebastian

        #4
        Re: Simple toString() problem

        On Sun, 07 Sep 2003 23:37:44 +0930, Ying Yang wrote:
        [color=blue]
        >[color=green][color=darkred]
        >> > Hi,
        >> >
        >> > <code snippet>
        >> > char* Car::toString()
        >> > {
        >> > //Example [XR, Holden]
        >> > char* str = {"[", carID, ",", carName, "]"};
        >> > return str;
        >> > }
        >> >
        >> > Note: carID and carName are private variables of class Car[/color]
        >>
        >> Use an ostringstream, and switch to using std::string for the return[/color]
        > value.[color=green]
        >>
        >> ostringstream oss;
        >> oss << '[' << carID << ',' << carName << ']'; // just like using cout
        >> return oss.str();
        >>
        >> If you /must/ use C-style strings, you're going to have to tackle dynamic
        >> memory management. That's a whole 'nother discussion, though.
        >>
        >> Josh[/color]
        >
        > What do i have to include to use ostringstream oss??[/color]

        <sstream>.
        [color=blue]
        > doesn't not seem like a
        > normal way of doing it with pointers to char.[/color]

        No, it uses C++-style strings, which is why I said to switch your return
        type to std::string. Pointers to char is not the normal way, it is the C
        way. In a C++ program, you should use std::string.

        Josh

        Comment

        • Jon Bell

          #5
          Re: Simple toString() problem

          In article <bjfds8$12du$1@ ulysses.noc.ntu a.gr>,
          Dimitris Kamenopoulos <dkamen4spam@cs lab.ece.ntua.gr > wrote:[color=blue]
          >
          >2) How you could do it with old-styled stuff:
          >//first you would need a buffer:
          >char * buf = new char[30]; //let's say a 30 character buffer
          >//then fill the buffer
          >sprintf(buf, "[%s,%s]", carId, carName); //sprintf requires #include <cstdio>
          >return buf;
          >
          >
          >Notice that I allocated buf with new, otherwise it would be destroyed as
          >soon as toString() exits and the returned pointer would point to nowhere.[/color]

          And of course you need to make sure to deallocate the memory at some point
          using 'delete', otherwise your program has a memory leak.

          --
          Jon Bell <jtbellap8@pres by.edu> Presbyterian College
          Dept. of Physics and Computer Science Clinton, South Carolina USA

          Comment

          • Thomas J. Clancy

            #6
            Re: Simple toString() problem

            "Ying Yang" <YingYang@hotma il.com> wrote in message
            news:3f5b3678_1 @news.iprimus.c om.au...[color=blue]
            > Hi,
            >
            > <code snippet>
            > char* Car::toString()
            > {
            > //Example [XR, Holden]
            > char* str = {"[", carID, ",", carName, "]"};
            > return str;
            > }
            >
            > Note: carID and carName are private variables of class Car
            >[/color]

            Here is a simple way to do what you want, but you will need to delete the
            memory allocated by your toString() externally.

            char* Car::toString()
            {
            char *tmpString = new char[255]; // for example some large buffer to hold
            info.
            sprintf(tmpStri ng, "[%ld,%s], carID, carName);
            return tmpString;
            }

            int main()
            {
            Car car;
            ...
            char *str = car.toString();
            cout << str << endl;
            delete str; // important to delete what toString() allocated.
            }

            Now you could always use std::string() to do this.

            std::string Car::toString()
            {
            std::ostringstr eam ss;
            ss << "[" << cardID << "," << carName << "]";
            return ss.str();
            }

            int main()
            {
            Car car;
            ...

            // no messy dealing with or deleting pointers.
            //
            cout << car.toString() << endl;
            }

            The important thing to remember is that you were declaring a pointer to a
            char in you toString() method, which is local to that method. Once the
            method returns that pointer is no longer valid, nor is the memory to which
            it is pointing. You need to allocate and return, which can be done in the
            first example the C way or in the second example, managed by objects, the
            C++ way.

            Tom


            Comment

            • Lem

              #7
              Re: Simple toString() problem

              1) you cannot assign char * variables this way
              2)as str is created on the local stack, it will be automatically destroyed
              when the function returns.
              Hope this helps

              Lem


              "Ying Yang" <YingYang@hotma il.com> wrote in message
              news:3f5b3678_1 @news.iprimus.c om.au...[color=blue]
              > Hi,
              >
              > <code snippet>
              > char* Car::toString()
              > {
              > //Example [XR, Holden]
              > char* str = {"[", carID, ",", carName, "]"};
              > return str;
              > }
              >
              > Note: carID and carName are private variables of class Car
              >
              > Compile Error: Car.cpp initializer for scalar variable requires one[/color]
              element[color=blue]
              >
              > Basically, the toString() method doesn't work. Any help appreciated. Note,
              > I'm not interested in working with the newer string data type because I[/color]
              want[color=blue]
              > to learnto do it with pointers to char.
              >
              >
              > Regards
              > wewewe
              >
              >
              >
              >
              >
              >
              >[/color]


              Comment

              • A

                #8
                Re: Simple toString() problem


                "Josh Sebastian" <curien@cox.net > wrote in message
                news:pan.2003.0 9.07.14.10.35.3 56798@cox.net.. .[color=blue]
                > On Sun, 07 Sep 2003 23:37:44 +0930, Ying Yang wrote:
                >[color=green]
                > >[color=darkred]
                > >> > Hi,
                > >> >
                > >> > <code snippet>
                > >> > char* Car::toString()
                > >> > {
                > >> > //Example [XR, Holden]
                > >> > char* str = {"[", carID, ",", carName, "]"};
                > >> > return str;
                > >> > }
                > >> >
                > >> > Note: carID and carName are private variables of class Car
                > >>
                > >> Use an ostringstream, and switch to using std::string for the return[/color]
                > > value.[color=darkred]
                > >>
                > >> ostringstream oss;
                > >> oss << '[' << carID << ',' << carName << ']'; // just like using cout
                > >> return oss.str();
                > >>
                > >> If you /must/ use C-style strings, you're going to have to tackle[/color][/color][/color]
                dynamic[color=blue][color=green][color=darkred]
                > >> memory management. That's a whole 'nother discussion, though.
                > >>
                > >> Josh[/color]
                > >
                > > What do i have to include to use ostringstream oss??[/color]
                >
                > <sstream>.
                >[color=green]
                > > doesn't not seem like a
                > > normal way of doing it with pointers to char.[/color]
                >
                > No, it uses C++-style strings, which is why I said to switch your return
                > type to std::string. Pointers to char is not the normal way, it is the C
                > way. In a C++ program, you should use std::string.
                >
                > Josh[/color]

                Just found out that Dev c++ 4.0 doesn't have the header file name
                <sstream> - great!

                wewewe


                ---
                Outgoing mail is certified Virus Free.
                Checked by AVG anti-virus system (http://www.grisoft.com).
                Version: 6.0.510 / Virus Database: 307 - Release Date: 14/08/2003


                Comment

                • Kevin Goodsell

                  #9
                  Re: Simple toString() problem

                  Lem wrote:

                  Please do not top-post. Re-read section 5 of the FAQ for posting guidelines.


                  [color=blue]
                  > 1) you cannot assign char * variables this way
                  > 2)as str is created on the local stack, it will be automatically destroyed
                  > when the function returns.[/color]

                  That's not necessarily relevant. This is perfectly legal:

                  char *func()
                  {
                  char *p = "some string";
                  return p;
                  }

                  The fact that p goes out of scope does not make the returned value
                  invalid. If the thing it pointed to was also going out of scope, then
                  there'd be a problem.

                  -Kevin
                  --
                  My email address is valid, but changes periodically.
                  To contact me please use the address from a recent posting.

                  Comment

                  • A

                    #10
                    Re: Simple toString() problem


                    [color=blue]
                    > Ying Yang wrote:
                    >[color=green]
                    > > Hi,
                    > >
                    > > <code snippet>
                    > > char* Car::toString()
                    > > {
                    > > //Example [XR, Holden]
                    > > char* str = {"[", carID, ",", carName, "]"};[/color]
                    >
                    > The way I see it, you want to return something like:
                    >
                    > "[carId,carName]"
                    >
                    > with the real values of carId and carName, of course. I assume carId and
                    > carName are also char*.
                    >
                    > Well,
                    > 1) {"[", carID, ",", carName, "]"} is basically the syntax for an array of
                    > stuff (presumably char* if carId and carName are also char*). In other
                    > words, if we call it str, its contents are:
                    > str[0] == "{"
                    > str[1] == carId
                    > str[2] == ","
                    > str[3] == carName
                    > str[4] == "]"
                    >
                    > Anyway, its type is char*[5] not char*, which is why you are getting the
                    > error. You are trying to assign an array to a scalar variable.[/color]

                    Here you are creating an array of characters, and the compiler will not like
                    it since it's expecting you to return a pointer to a char (char*). Any
                    suggestions?

                    [color=blue]
                    > 2) How you could do it with old-styled stuff:
                    > //first you would need a buffer:
                    > char * buf = new char[30]; //let's say a 30 character buffer
                    > //then fill the buffer
                    > sprintf(buf,"[%s,%s]", carId, carName); //sprintf requires #include[/color]
                    <cstdio>[color=blue]
                    > return buf;[/color]

                    I need something that will allow concatentation as I may have more than one
                    car to print out, and I don't think sprintf will do concatenation of
                    buffers.

                    wewewe


                    ---
                    Outgoing mail is certified Virus Free.
                    Checked by AVG anti-virus system (http://www.grisoft.com).
                    Version: 6.0.510 / Virus Database: 307 - Release Date: 14/08/2003


                    Comment

                    • A

                      #11
                      Re: Simple toString() problem


                      "Kevin Goodsell" <usenet1.spamfr ee.fusion@never box.com> wrote in message
                      news:feV6b.3350 $Yt.1699@newsre ad4.news.pas.ea rthlink.net...[color=blue]
                      > Lem wrote:
                      >
                      > Please do not top-post. Re-read section 5 of the FAQ for posting[/color]
                      guidelines.[color=blue]
                      >
                      > http://www.parashift.com/c++-faq-lite/
                      >[color=green]
                      > > 1) you cannot assign char * variables this way
                      > > 2)as str is created on the local stack, it will be automatically[/color][/color]
                      destroyed[color=blue][color=green]
                      > > when the function returns.[/color]
                      >
                      > That's not necessarily relevant. This is perfectly legal:
                      >
                      > char *func()
                      > {
                      > char *p = "some string";
                      > return p;
                      > }[/color]

                      but i need

                      char *p = "some string" + carID + carName; // but this gives error. what to
                      do?

                      wewewe



                      ---
                      Outgoing mail is certified Virus Free.
                      Checked by AVG anti-virus system (http://www.grisoft.com).
                      Version: 6.0.510 / Virus Database: 307 - Release Date: 14/08/2003


                      Comment

                      • Dimitris Kamenopoulos

                        #12
                        Re: Simple toString() problem

                        A wrote:

                        [color=blue]
                        > Here you are creating an array of characters, and the compiler will not
                        > like it since it's expecting you to return a pointer to a char (char*).
                        > Any suggestions?[/color]

                        I suppose you mean the line
                        char * buf = new char[30];

                        Yes, I am creating an array of pointers but buf points to its beginning.
                        Perfectly OK. In any case, the distinction between a char* and a char[] (in
                        general a T* and a T[]) is not always very clear. IIRC the C (and probably
                        the C++) FAQ explains when you can use a pointer as an array and vice
                        versa.
                        [color=blue][color=green]
                        >> 2) How you could do it with old-styled stuff:
                        >> //first you would need a buffer:
                        >> char * buf = new char[30]; //let's say a 30 character buffer
                        >> //then fill the buffer
                        >> sprintf(buf,"[%s,%s]", carId, carName); //sprintf requires #include[/color]
                        > <cstdio>[color=green]
                        >> return buf;[/color]
                        >
                        > I need something that will allow concatentation as I may have more than
                        > one car to print out, and I don't think sprintf will do concatenation of
                        > buffers.[/color]

                        But it will:
                        sprintf(concate nated_buf, "%s%s", buf1,buf2);

                        provided concatenated_bu f points to an array large enough to store the
                        characters of buf1 and buf2 and a trailing '\0'. Anyway, if you have to
                        print many cars, why should you first put the WHOLE output into one buffer?
                        Just print them one by one:

                        char * buf;
                        for (/*every car*/){
                        buf = car.toString();
                        printf("%s\n",b uf);
                        delete[] buf; //remember it was allocated with new[]
                        }

                        Comment

                        • Shane Beasley

                          #13
                          Re: Simple toString() problem

                          "A" <A@iprimus.com. au> wrote in message news:<3f5c18b7_ 1@news.iprimus. com.au>...
                          [color=blue]
                          > Just found out that Dev c++ 4.0 doesn't have the header file name
                          > <sstream> - great![/color]

                          Compiler-specific issues are off-topic here, but since I happen to
                          know a little bit about this one:

                          Dev-C++ 4 comes with the Mingw32 port of GCC 2.95.2 for Windows.
                          <sstream> is available as a separate download for that version of GCC:

                          <http://gcc.gnu.org/fom_serv/cache/80.html>

                          Note that GCC 2.95.2 is almost four years old, whereas GCC 3.3.1 was
                          released last month and comes with the latest Mingw32 release,
                          available at <http://www.mingw.org/>. Perhaps an upgrade is in order.
                          :)

                          - Shane

                          Comment

                          • Lem

                            #14
                            Re: Simple toString() problem

                            I was refering to the array...=)

                            Lem

                            "Kevin Goodsell" <usenet1.spamfr ee.fusion@never box.com> wrote in message
                            news:feV6b.3350 $Yt.1699@newsre ad4.news.pas.ea rthlink.net...[color=blue]
                            > Lem wrote:
                            >
                            > Please do not top-post. Re-read section 5 of the FAQ for posting[/color]
                            guidelines.[color=blue]
                            >
                            > http://www.parashift.com/c++-faq-lite/
                            >[color=green]
                            > > 1) you cannot assign char * variables this way
                            > > 2)as str is created on the local stack, it will be automatically[/color][/color]
                            destroyed[color=blue][color=green]
                            > > when the function returns.[/color]
                            >
                            > That's not necessarily relevant. This is perfectly legal:
                            >
                            > char *func()
                            > {
                            > char *p = "some string";
                            > return p;
                            > }
                            >
                            > The fact that p goes out of scope does not make the returned value
                            > invalid. If the thing it pointed to was also going out of scope, then
                            > there'd be a problem.
                            >
                            > -Kevin
                            > --
                            > My email address is valid, but changes periodically.
                            > To contact me please use the address from a recent posting.
                            >[/color]


                            Comment

                            • Agent Mulder

                              #15
                              Re: Simple toString() problem


                              <Shane Beasley>[color=blue]
                              > Note that GCC 2.95.2 is almost four years old, whereas GCC 3.3.1 was
                              > released last month and comes with the latest Mingw32 release,
                              > available at <http://www.mingw.org/>. Perhaps an upgrade is in order.[/color]
                              </Shane Beasley>

                              I can't figure it out on the download page. Do I need:

                              gcc-ada-3.3.1-20030804-1.tar.gz 12461 kb Aug 07, 2003 21:02
                              gcc-core-3.3.1-20030804-1-src.tar.gz 12958 kb Aug 07, 2003 19:11
                              gcc-core-3.3.1-20030804-1.tar.gz 2220 kb Aug 07, 2003 19:26
                              gcc-g++-3.3.1-20030804-1-src.tar.gz 2660 kb Aug 07, 2003 16:04
                              gcc-g++-3.3.1-20030804-1.tar.gz 2169 kb Aug 07, 2003 19:38
                              gcc-g77-3.3.1-20030804-1-src.tar.gz 1451 kb Aug 07, 2003 15:52
                              gcc-g77-3.3.1-20030804-1.tar.gz 1696 kb Aug 07, 2003 19:53
                              gcc-java-3.3.1-20030804-1-src.tar.gz

                              or one of the many more others? My platform is WindowsME. I work
                              with Borland 5.5.1 now. I expect a file C++Win32.zip or something like
                              it but can't find it. Can someone help me out? Thank you.

                              -X


                              Comment

                              Working...