🔒 Locked
Variable type converting?
Advertisement
Original Post
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
Like so:
[Edited by - _fastcall on May 13, 2009 2:08:33 AM]
#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]
I'm not sure what you mean by "native C++", but there are definitely ways to do it without printf (and it's variants).
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
edit: required reading
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++.
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:
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(); 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';}
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).
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).
Hello,
Thanks for all the different options.
Ok..i'll try not to use ipoa.
Let me check these out...
Thanks,
progames25
Thanks for all the different options.
Ok..i'll try not to use ipoa.
Let me check these out...
Thanks,
progames25
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.
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)};
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.
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]
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).
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]
Quote: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.
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]
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.
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.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement