4

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 a c 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?

maxfridbe
  • 5,872
  • 10
  • 58
  • 80

3 Answers3

2

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);
sharptooth
  • 167,383
  • 100
  • 513
  • 979
1

I ended up using CString since it is memory managed:

CString cstr;
cstr.Format(_T("%.7g"),flt);
mValue = _bstr_t(cstr);
maxfridbe
  • 5,872
  • 10
  • 58
  • 80
0
_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);
Vasily Redkin
  • 584
  • 1
  • 3
  • 17
  • 1
    any chance you could explain what makes this code a valid answer to the question posed? A code-only question is often not that useful to people who just happen by this post later. – Andrew Barber Sep 22 '12 at 03:01
  • Hm, so the question was about locale-specific floating "point". Sorry. Then `_vsnwprintf_s` should be replaced with `_vsnwprintf_s_l`, passing appropriate locale object, obtained from [_create_locale()](http://msdn.microsoft.com/en-US/library/4zx9aht2%28v=vs.80%29.aspx). – Vasily Redkin Jun 05 '13 at 19:10