Developer community
0 votes
63 views
asked by Advisor (5.6k points) 1 7 14 | 63 views

1 Answer

0 votes
Best answer
There are two easy ways to do this: you can use the <cstdio> facilities or the <iostream> library. In general, you should prefer the <iostream> library.

The <iostream> library allows you to convert pretty much anything to a std::string using the following syntax (the example converts a double, but you could substitute pretty much anything that prints using the << operator):

 // File: convert.h
 #include <iostream>
 #include <sstream>
 #include <string>
 #include <stdexcept>
 
 class BadConversion : public std::runtime_error {
 public:
   BadConversion(const std::string& s)
     : std::runtime_error(s)
     { }
 };
 
 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
   return o.str();
 }

The std::ostringstream object o offers formatting facilities just like those for std::cout. You can use manipulators and format flags to control the formatting of the result, just as you can for other std::cout.

In this example, we insert x into o via the overloaded insertion operator, <<. This invokes the iostream formatting facilities to convert x into a std::string. The if test makes sure the conversion works correctly — it should always succeed for built-in/intrinsic types, but the if test is good style.

The expression o.str() returns the std::string that contains whatever has been inserted into stream o, in this case the string value of x.
answered by Geek (15.7k points) 5 9 21

Related questions

0 votes
1 answer
asked by albertina Geek (15.7k points) 5 9 21 | 85 views
0 votes
0 answers
0 votes
1 answer
asked by Smita Advisor (7.1k points) 10 23 42 | 121 views
0 votes
1 answer
asked by sagar Expert (12.3k points) 7 12 25 | 298 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users