Solved

newbie: numeric to string conversion

Posted on 2002-03-06
3
197 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

705 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