Solved

newbie: numeric to string conversion

Posted on 2002-03-06
3
196 Views
Last Modified: 2010-04-01
What is the best/accepted way to convert a numeric value (int, long, double, etc) into a string?

As a side note, is it possible to convert an unsigned char array into a string without "reinterpret_cast"ing it?  How?

Thanks
0
Comment
Question by:slyph
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 100 total points
ID: 6844626
The most flexible way would 'sprintf()', e.g.

#define MAX_LEN 20
char acString [ MAX_LEN];

int i = 3;
double d = 3.141;

sprintf ( acString, "%d", i); // int
sprintf ( acString, "%f", d); // double

The pure C++ way is using a stringstream

#include <sstream>
using namespace std;

int i = 3;
double d = 3.141;
char* pszString;

stringstream ss;

ss << i;

pszString = ss.str().c_str();

or

ss << d;

pszString = ss.str().c_str();
0
 
LVL 5

Expert Comment

by:yonat
ID: 6845079
You can also use a helper class like the stringizer I once wrote (http://ootips.org/yonat/4dev/stringizer.h).
Then you'll have a nicer syntax:
  string msg = "The int variable i is " + stringize(i) + ", and the float variable f is " + stringize(f);
0
 

Author Comment

by:slyph
ID: 6845293
Perfect, thanks.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question