cast float to wchar_t win32

Айм*_*мед 2 c++ windows winapi visual-studio-2012

它吓坏了我,我无论如何都找不到把漂浮物扔给wchar_t,或者我看错了地方!

 float cNumbers[9]  = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0};
 float x            = 3.0;
 float temp     = 0.0;
 wchar_t data[]     = {0};

 for(int i=0; i < sizeof(cNumbers); i++){

    temp = x / cNumbers[i];
    bool isInt = temp == static_cast<int>(temp);

    if(isInt){
        data =  temp; //this is a big fail
        addToList(hWnd,data);
    }
  }

void addToList(HWND hWnd,const wchar_t * data ){

  SendMessage(GetDlgItem(hWnd,IDC_LISTBOX),LB_ADDSTRING,0,(LPARAM)data); 
}
Run Code Online (Sandbox Code Playgroud)

问题是我想将浮点值转换为wchar_t以将其发送到列表框

Tim*_*sch 5

在C++中,转换POD会将二进制数据重新解释为转换类型,而不是您要完成的类型转换.

你有几个选择:

  • 您可以使用boost::lexical_cast类似角色的转换
  • 您可以使用wsprintfstd::wstringstream来处理从float到wide string的转换
  • 如果您使用的是MFC/ATL,则可以使用CString :: Format将float转换为字符串

第二个选项是唯一一个不使用第三方库的选项,因此,如果您在库中明智地使用了什么,那么您将无法使用wsprintf或者使用std :: wstringstream.通常我在这种情况下的建议是使用std :: wstringstream来保证类型安全和缓冲区溢出的保护.