Solved

newbie: numeric to string conversion

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

707 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now