Converting a VARIANT variable to int or float...?

  • Thread starter Thread starter Teis Draiby
  • Start date Start date
T

Teis Draiby

I want to print a variable of the type 'VARIANT' to the console using
'cout'. How do I convert this variable to something that 'cout' understands?

Thank you in advance, Teis
 
I am also curious to know how do I determine the data type of the VARIANT
variable?

I've been searching for information on how to handle VARIANT variables but
with very little success. Any links are also appreciated.

Thank you very much, Teis
 
Hi Teis,

Teis Draiby said:
I want to print a variable of the type 'VARIANT' to the console using
'cout'. How do I convert this variable to something that 'cout'
understands?

You could overwrite operator<< for std::ostream and VARIANT like so:

std::ostream& operator<<(std::ostream& ostr, const VARIANT& v)
{
USES_CONVERSION_EX;

// vt holds the current type of the variant's value
switch(v.vt)
{
case VT_I1:
ostr << v.cVal;
break;

case VT_I2:
ostr << v.iVal;
break;

case VT_I4:
ostr << v.lVal;
break;

case VT_R4:
ostr << v.fltVal;
break;

case VT_R8:
ostr << v.dblVal;
break;

case VT_BSTR:
ostr << OLE2A_EX(v.bstrVal, 2000);
break;

// too lazy for other types, so one could try to get the system do a
string conversion:
default:
CComVariant vDest;
if(SUCCEEDED(VariantChangeTypeEx(&vDest, v, GetUserDefaultLCID(), 0,
VT_BSTR))
ostr << OLE2A_EX(vDest.bstrVal, 2000);
break;
}

return ostr;
}


HTH,
SvenC
 
Uupsi,
std::ostream& operator<<(std::ostream& ostr, const VARIANT& v)

correct this to:
std::ostream& operator<<(std::ostream& ostr, VARIANT& v)

if(SUCCEEDED(VariantChangeTypeEx(&vDest, v, GetUserDefaultLCID(), 0,
VT_BSTR))

and this to:
if(SUCCEEDED(VariantChangeTypeEx(&vDest, &v, GetUserDefaultLCID(), 0,
VT_BSTR)))


Bye,
SvenC
 
Great. You saved my day(s).
Thank you for the very detailed answer.

Teis


btw, where's ".tfg"??
 
Back
Top