Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,220 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,230 people online right now. Registration is fast and FREE... Join Now!





Convert Template

Converts between types using string stream

Submitted By: jwwicks
Actions:
Rating:
Views: 196

Language: C++

Last Modified: August 5, 2008

Snippet


  1. #include <string>
  2. #include <sstream>
  3. #include <iostream>
  4. #include <iomanip>
  5.  
  6. using namespace std;
  7.  
  8. template <class oType, class iType>
  9. oType ioConv( const iType& _T )
  10. {
  11.         stringstream _S;
  12.         oType ret_val;
  13.  
  14.         _S << _T;
  15.         _S >> ret_val;
  16.  
  17.         return ret_val;
  18. }
  19.  
  20.  
  21. int main( int argc, char* argv[] )
  22. {
  23.         char buffer[3][20] = { "1", "23.45", "Hello World..." };
  24.         int i =0;
  25.         double d = 0.0;
  26.         string s;
  27.         string s2;
  28.  
  29.         i = ioConv<int>(buffer[0]);
  30.         d = ioConv<double>(buffer[1]);
  31.         s = ioConv<string>(buffer[2]);
  32.         s2 = ioConv<string>(d);
  33.  
  34.         cout << "I:  " << i << endl;
  35.         cout << "D:  " << d << endl;
  36.         cout << "S:  " << s << endl;
  37.         cout << "S2: " << s2 << endl;
  38.  
  39.         return 0;
  40. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month