简体   繁体   中英

float to _bstr_t

I know I can create a _bstr_t with a float by doing:

mValue = _bstr_t(flt); 

And I can format the float string by first declaring ac string:

char* str = new char[30];
sprintf(str, "%.7g", flt); 
mValue = _bstr_t(str);

I am a bit rusty on c++, especially when it comes to _bstr_t which is A C++ class wrapper for the Visual Basic string type. Will the memory pointed to by str be managed by the _bstr_t object? My problem is passing the float (flt) into the constructor of the _bstr_t causes a float with a number 33.03434 to turn into "33,03434" if for instance my current language set is Italian. Is there another way to declare it perhaps?

When you create a _bstr_t instance using a conversion from char* a new BSTR is created, the object doesn't take ownership of memory pointed to by char* . You'll have to manage the memory pointed to by char* yourself.

In you case since you know that there's a limit on how long a produces string can be your best bet is to allocate the buffer on stack:

const int bufferLength = 30;
char str[bufferLength] = {};
snprintf(str, bufferLength - 1, "%.7g", flt); 
mValue = _bstr_t(str);

I ended up using CString since it is memory managed:

CString cstr;
cstr.Format(_T("%.7g"),flt);
mValue = _bstr_t(cstr);
_bstr_t FormatBstr(LPCWSTR FormatString, ...)
{
    ATLASSERT( AtlIsValidString(FormatString) );
    unsigned int len = 10 + wcslen(FormatString);
    unsigned int used = 0;

    BSTR r = ::SysAllocStringLen(NULL, len);

    va_list argList;
    va_start( argList, FormatString );
    while(len < 2048) {
            used = _vsnwprintf_s(r, len+1, _TRUNCATE, FormatString, argList);
            if(used < len)
                    break;
            len += 10; // XXX
            ::SysReAllocStringLen(&r, NULL, len);
    }
    va_end( argList );
    ::SysReAllocStringLen(&r, r, used);
    return _bstr_t(r, false);
}

then

sprintf(str, "%.7g", flt); 
mValue = FormatBstr(L"%.7g", flt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM