Menu

Building integer into string class

dev_15
2007-08-21
2012-09-26
  • dev_15

    dev_15 - 2007-08-21

    Hi, this is one of the questions from Bruce Ekels thinking in C++ book, chapter 12, question 14, i have only posted the first part of the question that i am stuck with.

    How do you combine an integer into the string class in C++?

    Write a class called Bird that contains a string member and a static int. In the default constructor, use the int to automatically generate an identifier that you build in the string, along with the name of the class (Bird #1, Bird #2, etc.).

    Thanks

     
    • Anonymous

      Anonymous - 2007-08-21

      I think the idea is that the integer is a static member. In the constructor it is incremented and then writeen to the string; that's the easy part. This way every instance has a unique numeric identifier in its string.

      Oh... and teh easy part:

      For a class with members:

      static int index ;
      std::string id_string ;

      in the constructor you write the string thus:

      index++ ;
      id_string << "Bird #" << index ;

      The string::operator<< is overloaded for const char* and int (amongst others), so it is as simple as that.

      Clifford

       
    • dev_15

      dev_15 - 2007-08-22

      The compiler i'm using VC++ is saying:

      error C2676: binary '<<' : 'std::string' does not define this operator or a conversion to a type acceptable to the predefined operator

       
    • Soma

      Soma - 2007-08-22

      Clifford loses track of his train of thought from time to time.

      Search for 'std::ostringstream' and the 'std::ostringstream::str' method.

      Soma

       
    • Anonymous

      Anonymous - 2007-08-22

      Doh! I am an idiot. Sorry.

      Seeing as this is a Bloodshed/Dev-C++ forum, it would have been worth mentioning that you were using VC++ just out of courtesy.

      Take a look at the example here: http://www.cplusplus.com/reference/iostream/ostringstream/ostringstream.html

      Clifford

       
    • Soma

      Soma - 2007-08-23

      Well, it's not as if you are absolutely wrong. It just needs some support code.

      Soma

      template
      <
      typename Type_t
      >
      std::string &
      operator <<
      (
      std::string & lhs_p,
      const Type_t & rhs_p
      )
      {
      std::ostringstream support;
      support << rhs_p;
      lhs_p += support.str();
      return(lhs_p);
      }

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.