dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Feb 2, 2001

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


I/O Formatting With Stringstream


The sprintf() function isn't type-safe, it doesn't support user-defined types and it's a common source of buffer overflow bugs. In C++, there's a better alternative to sprintf(), namely stringstream objects. The following function template accepts a value of any type and writes it into a user-supplied string s:
 
#include 
using namespace std;
template 
void string_fmt(string & s, const T & t)
{
  ostringstream oss; // create a stream
  oss << t; // insert t to buffer
  s=oss.str(); // copy stream's string 
}

In the following example, the value 10.76 is written into the string s using the string_fmt() function template:
 
string s;
string_fmt(s,10.76);

The following cast_stream function template performs the opposite operation. It converts a variable of type in_value to a variable of type out_type. In the following example, cast_stream converts a string to a double:
 
template 
out_type cast_stream(const in_value & t)
{
 std::stringstream ss;
 ss << t; // first insert value
 out_type ret; // value will be converted to out_type
 ss >> ret; // write value to ret
 return ret;
}

string s=
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date