Solved

newbie: numeric to string conversion

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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Quicksort a dynamic deque 33 72
how to understand recursion 12 224
C Language combined operators 28 109
ASP.net build a IF/Then Walkthrough Guide 1 209
Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

808 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