"Vijai Kalyan" <vi**********@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Re: Using std::strinstream to convert a char to int
That doesn't make any sense. Type 'char' objects
already are integers. stringstreams are for working
with strings. Neither a 'char' nor an 'int' are strings.
More below.
I wrote the following function as a curiosity:
template<typename SourceType,
typename DestinationType>
DestinationType NumericCast(const SourceType& value) {
std::wstringstream strbuf;
strbuf << value << std::endl ;
strbuf.flush();
DestinationType convalue;
strbuf >> convalue;
return convalue;
}
This works fine for all numeric types such as int to long, long to
float etc.
However, I tried the following:
NumericCast<char, int>('c');
This failed to return the correct value.
That's because you probably don't understand what
'correct value' means with a stringstream as you're
using it.
When I stepped through the
function, the value of "convalue" remained the same throughout. But
this happened only when SourceType was char. A
I tried stepping into the operator code, but my debugger just stepped
over so I am not sure what's going on inside.
Anyone have any ideas on anything I am doing that is obviously wrong,
but which I am missing?
If you want to convert a type 'char' to a type 'int', simply write:
char c = 42;
int i = 0;
i = c;
What you're probably not realizing is that what a stringstream
does with numeric objects is translate the *text* representation
of a value (e.g "123") to its binary representation ( int(123) ),
or the inverse conversion ( int(123) to "123"). Sinc both 'char'
and 'int' are already numeric types, there's no text involved.
There's a reason that type 'stringstream' has the word 'string'
as part of its name. :-)
-Mike