Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [C++] String Composing Tip
Index -> Programming, C++ -> C++ Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Tue Mar 16, 2004 8:50 pm   Post subject: [C++] String Composing Tip

For composing long strings the temptation is to use the std::string class and its + operator. However, this results in a temporary std::string object being created each time the operator is used. Sometimes compilers can optimize this away, but it shouldn't be counted on.

Instead use the std::stringstream class.

code:
#include <sstream>
#include <iostream>

int main()
{
   std::stringstream ss;

   ss << "hello";
   ss << " ";
   ss << "world" << std::endl;

   std::cout << ss.str();

   return 0;
}


The same way you should use operator overloading to handle output, you can overload it to handle interactions with std::stringstream.

code:
#include <sstream>

class my_class
{
   private:
      int a, b;
   public:
      my_class(int, int);
      friend std::stringstream& operator<<(std:stringstream&, const my_class&);
};

int main()
{
   std::stringstream ss;
   my_class c(4, 3);

   ss << c << std::endl;

   return 0;
}

my_class:my_class(int init_a = 0, int init_b = 0)
: a(init_a), b(init_b)
{ }

std::stringstream& operator<<(std:stringstream& s, const my_class& m)
{
   return s << m.a << " " << m.b;
}
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, C++ -> C++ Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: