2013-02-17 71 views
2

它嚇壞了我,我無法找到將浮點數轉換爲wchar_t或者我正在尋找錯誤的地方!cast float to wchar_t win32

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); 
} 

的問題是,我想浮點值轉換爲wchar_t的將其發送到列表框中

+0

用VS2012還可以使用'的std :: to_wstring(X)'轉換爲'wstring'。 – 2013-02-17 22:17:14

+0

[你可以使用什麼將一個int/float轉換爲wchar \ _t \ *?](http://stackoverflow.com/questions/1860945/what-c​​an-you-use-to-cast-an -int-float到一個-WCHAR-T) – Deanna 2013-02-19 14:24:17

回答

5

在C++中,鑄造莢會重新解釋的二進制數據作爲所述鑄造鍵入與不做的那種類型的您想要完成的轉換。

你有幾個選擇這裏:

  • 可以使用boost::lexical_cast的鑄像轉換
  • 可以使用wsprintfstd::wstringstream處理從float轉換爲寬字符串
  • 如果您正在使用MFC/ATL,你可以使用的CString ::格式的浮動轉換爲字符串

第二個選項是唯一一個不使用第三方庫,所以如果受限於可以使用庫的方式,則可能會遇到wsprintf或std :: wstringstream。通常我建議在這種情況下使用std :: wstringstream來實現類型安全性和緩衝區溢出保護。

3

已經有一個答案:What can you use to cast an int/float to a wchar_t*?

只需使用:

float x = 0.0f; 

std::wostringstream woss; 
woss << x;  
std::wstring ws = woss.str(); 
const wchar_t* cwc = ws.c_str(); 
std::vector<wchar_t> buf(cwc , cwc + (ws.size() + 1)); 
wchar_t* x2 = &buf[0];