On Wed, 07 Jan 2004 19:39:14 +0530, Venkat wrote:
Hi All,
I want to typecast int to std::string how can i do it.
Here is the sample code.
int NewList[500];
//Fill the NewList with integers values.
......
......
//Replace the file contents with new list values at a specified location.
int i=0;
std::string line;
ifstream inFile(sample);//opens a file to read
while (getline (inFile, line) )
{
int comma1Pos = line.find(',');
int comma2Pos = line.find(',', comma1Pos+1);
int numChars = comma2Pos - comma1Pos - 1;
line.erase(comma1Pos+1, numChars); //
line.insert(comma1Pos+1, (std::string)NewList[i]);
i++;
}
inFile.close();
In the above code the function insert takes 2nd argument as a string so i
was trying to type cast NewList[i] to string.
The complier throws a type cast error saying type cast int to string is not
possible.
Is there any way i can type cast the same.
No, that is not what casting is about. Casting can change something to
something related. Although for humans integers and their
string-representations may be related, for computers they are very
different.
As a side note, you should never use C-style casts in C++, C++ has much
better casts: static_cast<>, dynamic_cast<>, const_cast<> and
reinterpret_cast<>. Familiarize yourself with those and never use the
C-style casts again. It will save you a lot of grief.
So the question now becomes, how to convert a number to a string. Thee are
a number of ways to do so, the easiest and most C++ish:
#include <sstream>
std::string toString(int i)
{
std::stringstream s;
s << i;
return s.c_str();
}
OK, this works, but maybe you want to use this for unsigned ints as well.
Or for longs. You could create the same function multiple times,
overloading on the argument:
std::string toString(long) { ... }
std::string toString(unsigned int) { ... }
std::string toString(unsigned long) { ... }
std::string toString(float) { ... }
std::string toString(double) { ... }
Fortunately, there is an easier way. We can get the compiler to do it for
us by using the magic of templates:
template<typename T>
std::string toString(T t)
{
std::stringstream s;
s << t;
return s.c_str();
}
This will make the compiler produce all of the above functions
automagically, but only the ones we actually use! (Do note that this code
must be 'seen' by the compiler before you use it, you cannot just use a
prototype and define the function in another C++ file. So this typically
goes in some header.)
So if you use toString(i), where i is an integer, the compiler will
substitute int for T and we end up with exectly the same as above. But if
we use toString(l), where l is a long, the compiler automagically
generates the above for a long. Templates can be so incredibly powerful!
HTH,
M4