int integerToConvert;
char foo[4];
string ConvertIntoThis;
sprintf(foo, "%d", integerToConvert)
ConvertIntoThis = foo;
And it works! But, what if I don't know how big the integer is. The code
above will only work for integers of length 4. What is a way around this?
All you have to do is figure out the length of the longest string that
will result from the conversion. For integral types, look at the minimum
and maximum values that that type can hold.
--
Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Use the standard c++ string and ostringstream classes :-
std::ostringstream str;
str << integerToConvert;
std::string foo = str.str();
Something possibly better:
#include <iostream>
#include <cstdio>
std::string i2s(const int number)
{
static char temp[1024];
std::sprintf(temp, "%d", number);
return std::string(temp);
}
int main()
{
using namespace std;
string number=i2s(121);
cout<<number<<endl;
}
Ioannis
--
* Ioannis Vranos
* Programming pages: http://www.noicys.f2s.com
* Alternative URL: http://run.to/noicys
If you're interested in a completely different approach, try using a
std::ostringstream to convert the integer into a std::string:
#include <string>
#include <sstream>
int integerToConvert;
std::string ConvertIntoTnis;
std::ostringstream ConversionStream;
ConversionStream << integerToConvert; // just like writing to cout
ConvertIntoThis = ConversionStream.str(); // extract the resulting string
The std::string automatically expands to accommodate however many
characters are necessary.
--
Jon Bell <jtb...@presby.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
I often add a function like this to my projects, it makes life a lot easier
when I want to output quick debugging string and similar.
template <class T> string ToString(const T& var)
{
ostringstream str;
str << var;
return str.str();
}
Your array is too small. Try making it the maximum size that an integer
can possibly be. 8 digits? Somewhere around there.
Why not cross-post these postsings to ut.cdf.csc228h? I'm sure the
other ppl taking the course are asking the same questions.
-Patrick
>
>
>
>
--
pat...@tendim.cjb.net
http://www.tendim.cjb.net/
Like anime? Got hotline?
hotline://twoaday.cjb.net/
>All you have to do is figure out the length of the longest string that
>will result from the conversion. For integral types, look at the minimum
>and maximum values that that type can hold.
See std::numeric_limits<T>::digits10
> static char temp[1024];
Waste.