compboy said:
Can anyone help me about this.
I have been trying all the ways I knew and I could find but just didnt
work.
I have tried:
using itoa but it says that it doesnt have that function.
and also
String aa = 34;
cout << aa.val() <endl;
but again just didnt work out it even cant find the String as a
declaration.
I tried to change it into string but still didnt work
and I tried to do it like c:
aa = 30+" ";
and still didnt work.
just for information that I have included all the libraries I need for
those functions mentioned above.
Thanks a lot.
The way I do it is using stringstreams.
You need to
#include <sstream>
std::string aa;
int Value = 34;
Now say I want to get value, which is an int, into the string as the
characters "34"
std::stringstream ConvertStream;
ConvertStream << Value;
ConvertStream >> aa;
At this point the std::string aa contains the text "34" if all went well.
I find this so useful, in fact, that I have found a template that I use.
This is my template:
template<typename T, typename F > T StrmConvert( F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}
template<typename F> std::string StrmConvert( F from )
{
return StrmConvert<std::string>( from );
}
First, to talk about the first template, which takes two typenames. One is
what to convert To, the other is what to convert from. I could do the same
thing as before doing this:
std::string aa;
int Value = 34;
aa = StrmConvert<std::string>( Value );
I find, however, that most of the time I am converting some type of number
to std::string and I got tired of always specifying std::string, so that's
where the specialized template comes from. If I don't specify what to
convert to, it converts it to std::string, so then it becomes even shorter:
std::string aa;
int Value = 34;
aa = StrmConvert( Value );
But I could still go the other way if I wanted, std::string to number:
Value = StrmConvert<int>( aa );
This works for all built in types such as int, float, double, char, etc...
The observant may notice that I am not doing any error checking in the
template. That is, if the string was "xyz" and I tried to convert it to a
number the stringstream would be in an error condition. Because of the
line:
T to = T();
the to variable is being default initialized. If it's int, double, char, it
will be set to 0. std::string "", etc...