Skip to main content
gamedev.net
🔒 Locked

Variable type converting?

Started by Progames25 May 12, 2009 at 10:51 PM 25 replies 2.9k views
Original Post
Progames25
Progames25
Hello, I was wondering if in native C++ there are any ways to convert integers to characters or strings? I searched google but all I found was using printf and stuff like that but that would not work in the case of how i'm using the variables, I need an integer varibale's value in a char parameter. Thanks, Progames25
-----------------------------I use C++ and DirectX.I'm new to game programming.
fastcall22
fastcall22
Like so:

#include <sstream>#include <string>template<class Type>std::string Stringify( const Type& input ){	std::stringstream ss;	ss << input;	return ss.str();}


[Edited by - _fastcall on May 13, 2009 2:08:33 AM]
ChaosEngine
ChaosEngine
what do you mean "native" c++? There's nothing built into the language itself, but there are plenty of options in the standard library. Assuming you want the integer 123 to end up as a string "123", there are several ways. You can use a stringstream, sprintf, boost::lexical_cast or you can roll your own. If you're 100% sure you're working only in ascii, this is pretty trivial, but to be honest it's not really worth it. Just use one of the standard library ways and you'll be sweet.

edit: required reading
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
tnutty
tnutty
yes using the function itoa.

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/
Our whole life is a opengl application.
Aardvajk
Aardvajk
Quote:
Original post by tnutty
yes using the function itoa.


Note though that itoa is a non-standard extension, although widely supported.

It also requires that you pass in a buffer that is long enough to contain any possible value.

There is little or no reason to use itoa over a stringstream in C++.
phresnel
phresnel
If by "native C++" you mean only the core language and without external libraries: Sure there is a way. To just present to you the simplest function, int to character:

char itoc (int i) {    if (i<0 || i>9)        throw some_invalid_conversion_exception();    static const char conv [] = {        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'    };    return conv ;}


There is also a version that works without a lookup, but it is not portable C++ and assumes that '0'..'9' are continous in underlying integer value (which is the case with most x86 compilers:

char itoc (int i) {    if (i<0 || i>9)        throw some_invalid_conversion_exception();    return i + '0';}
ApochPiQ
ApochPiQ
Eurgh.

Please, please, please do not use unsafe functions like itoa (buffer overflow exploits). Also, please do not roll your own lexical cast functions unless you know what you're doing. (See boost::lexical_cast - it's more complex than it sounds.)

Just use the tools provided to you in the language (stringstreams) or in well-respected libraries (boost::lexical_cast).
Progames25
Progames25
Hello,
Thanks for all the different options.
Ok..i'll try not to use ipoa.
Let me check these out...


Thanks,
progames25
-----------------------------I use C++ and DirectX.I'm new to game programming.
tnutty
tnutty
I never said that itoa was good to use. i was just answering his question.
Our whole life is a opengl application.
Antheus
Antheus
Quote:
I need an integer varibale's value in a char parameter.


So basically you have a char *, and you want to write several things to it, including some ints.

This would be accomplished with sprintf.
char buffer[1024];char * s = buffer;// note that s must be advanced to write in proper positions += sprintf(s, "%d", 10);s += sprintf(s, " %s ", "Hello World");s += sprintf(s, "%f", 3.14);printf(buffer);


But this is what stringstream acomplishes, just in a different way:
std::stringstream buf;buf << 10 << " Hello World " << 3.14;std::cout << buf.str();



sprintf approach is more straight-forward if one is given a char * into which to write the output.

stringstream should be preferred. But, to produce a C-style char * string, it is necessary to copy the results from 'buf.str().c_str()' into destination.
implicit
implicit
Out of curiosity, what's a good way to get a conservative estimate for the maximum number of digits in an integer when allocating compile-time buffers? I've used something like the following code snippet in the past, but I'd much prefer an approximation that someone has actually bothered to verify..
#define MAX_DIGITS(bits) ((size_t) (((bits) * 78UL + 255UL) >> 8))enum { UINT_DIGITS = MAX_DIGITS(sizeof(unsigned int) * CHAR_BIT), INT_DIGITS = 1 + MAX_DIGITS(sizeof(signed int) * CHAR_BIT - 1), // (excluding null)};
ApochPiQ
ApochPiQ
Quote:
Original post by tnutty
I never said that itoa was good to use. i was just answering his question.


Please remember that this is the For Beginners forum. The posters here are new to programming, and because of their lack of experience, they won't know how to tell what is a good solution and what isn't.

When you post something like your mention of itoa, the default assumption (on the part of the learner) is that you know what you are talking about and therefore itoa is an acceptable solution. If you know it's a bad solution, say so. Knowingly offering a bad solution to a problem - and not saying that it's a bad solution - is a real dick move.
ApochPiQ
ApochPiQ
Quote:
Original post by implicit
Out of curiosity, what's a good way to get a conservative estimate for the maximum number of digits in an integer when allocating compile-time buffers? I've used something like the following code snippet in the past, but I'd much prefer an approximation that someone has actually bothered to verify..
#define MAX_DIGITS(bits) ((size_t) (((bits) * 78UL + 255UL) >> 8))enum { UINT_DIGITS = MAX_DIGITS(sizeof(unsigned int) * CHAR_BIT), INT_DIGITS = 1 + MAX_DIGITS(sizeof(signed int) * CHAR_BIT - 1), // (excluding null)};


You should be able to do something like roundup(log10(number)) + 1 to get a solid estimate. Add 2 or 3 to be safe [smile]
Antheus
Antheus
Quote:
Original post by implicit
Out of curiosity, what's a good way to get a conservative estimate for the maximum number of digits in an integer when allocating compile-time buffers?


There are only 4 or so different sizes, just manually count them. Then add 1 for minus sign, the 1 for zero character.

For general solution, it's around log(2^n)/log(10) + 2. The 2 comes from 1 char for sign, one for \0. But evaluating this at compile-time might be non-trivial, since 2^n could/would overflow, depending on type, or it might be too large completely (128 bit integer).
ApochPiQ
ApochPiQ
Quote:
Original post by Antheus
Quote:
Original post by implicit
Out of curiosity, what's a good way to get a conservative estimate for the maximum number of digits in an integer when allocating compile-time buffers?


There are only 4 or so different sizes, just manually count them. Then add 1 for minus sign, the 1 for zero character.

For general solution, it's around log(2^n)/log(10) + 2. The 2 comes from 1 char for sign, one for \0. But evaluating this at compile-time might be non-trivial, since 2^n could/would overflow, depending on type, or it might be too large completely (128 bit integer).


Uh, that method tells me that 615 will require 187 digits [wink]
implicit
implicit
Quote:
Original post by ApochPiQ
You should be able to do something like roundup(log10(number)) + 1 to get a solid estimate. Add 2 or 3 to be safe [smile]
Well, that's exactly what the code is supposed to be doing. I'm just not quite certain whether it's completely safe, or overestimates any useful word size, is liable to cause integer overflows, and so forth. So I figured someone ought to have put some effort into figuring out a good solution, though perhaps this is a discussion best kept outside of the For Beginners forum.
At the end of the day you're going to have to deal with fixed-size buffers occasionally after all. Most recently I had to print some numbers from a signal handler, where you're barely allowed to sneeze, much less throw string objects around.
Antheus
Antheus
Quote:
Original post by ApochPiQ

Uh, that method tells me that 615 will require 187 digits [wink]


n = number of bits.

But this has gone off-topic enough methinks.
tnutty
tnutty
Quote:
When you post something like your mention of itoa, the default assumption (on the part of the learner) is that you know what you are talking about and therefore itoa is an acceptable solution. If you know it's a bad solution, say so. Knowingly offering a bad solution to a problem - and not saying that it's a bad solution - is a real dick move.


The best way for one to learn whats good or bad is for one to use it. If we tell
him (assuming a boy), that this is bad or that is bad, then it would just be
feeding him information without no experience. Its like going to school for
years and years but never getting the real practice in the field. I mean the only way he will figure out whats good and bad is with experience. When he experiences multiple error caused by itoa,he will realize how useful or not it actually is. Its not really a dick move, it has a hidden motive.
Our whole life is a opengl application.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.