Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

newbie: numeric to string conversion

Posted on 2002-03-06
3
Medium Priority
?
199 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 400 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

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
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 technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

604 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