VC++ (VS2013)裡面char和LPTSTR的轉換問題
阿新 • • 發佈:2019-02-06
孫鑫vc++第七課在VS2013裡面寫如下程式碼,實現兩個數的相加並且顯示結果:
因為編譯器認為_itot不安全所以換一個安全的_itot_s
這樣就可以了 t系列的型別和函式都是雙編譯,Unicode和MBCS的都可以用,最穩妥,所以微軟強烈推薦
int num1,num2,num3;
char ch1[10],ch2[10],ch3[10];
GetDlgItem(IDC_EDIT1)->GetWindowText(ch1,10);
GetDlgItem(IDC_EDIT2)->GetWindowText(ch2,10);
num1=atoi(ch1);
num2=atoi(ch2);
num3=num1+num2;
itoa(num3,ch3,10);
GetDlgItem(IDC_EDIT3)->SetWindowText(ch3);
編譯執行出現錯誤:
1>.\TestDlg.cpp(42) : error C2664: “int CWnd::GetWindowTextW(LPTSTR,int) const”: 不能將引數 1 從“char [10]”轉換為“LPTSTR” 1> 與指向的型別無關;轉換要求 reinterpret_cast、C 樣式轉換或函式樣式轉換 1>.\TestDlg.cpp(43) : error C2664: “int CWnd::GetWindowTextW(LPTSTR,int) const”: 不能將引數 1 從“char [10]”轉換為“LPTSTR” 1> 與指向的型別無關;轉換要求 reinterpret_cast、C 樣式轉換或函式樣式轉換 1>.\TestDlg.cpp(53) : error C2664: “CWnd::SetWindowTextW”: 不能將引數 1 從“char [10]”轉換為“LPCTSTR” 1> 與指向的型別無關;轉換要求 reinterpret_cast、C 樣式轉換或函式樣式轉換
原因是字符集的問題。VS2008和VC6.0還是有些不一樣的。
解決方案:
char 改成TCHAR
atoi 改成 _ttoi
itoa 改成 _itot
像上面這樣寫後在VS2013裡還是會報一個安全錯誤TCHAR ch1[10],ch2[10],ch3[10]; GetDlgItem(IDC_EDIT1)->GetWindowText((ch1),10); GetDlgItem(IDC_EDIT2)->GetWindowText((ch2),10); num1=_ttoi(ch1); num2=_ttoi(ch2); num3=num1+num2; _itot(num3,ch3,10); GetDlgItem(IDC_EDIT3)->SetWindowText(ch3);
1>c:\users\yc\documents\visual studio 2013\projects\mybole\mybole\testdlg.cpp(80): error C4996: '_itow': This function or variable may be unsafe. Consider using _itow_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> d:\program files\microsoft visual studio 12.0\vc\include\wchar.h(900) : 參見“_itow”的宣告
因為編譯器認為_itot不安全所以換一個安全的_itot_s
int num1, num2, num3;
TCHAR ch1[10], ch2[10], ch3[10];
GetDlgItem(IDC_EDIT1)->GetWindowTextW(ch1, 10);
GetDlgItem(IDC_EDIT2)->GetWindowTextW(ch2, 10);
num1 = _ttoi(ch1);
num2 = _ttoi(ch2);
num3 = num1 + num2;
_itot_s(num3, ch3, 10);
GetDlgItem(IDC_EDIT3)->SetWindowTextW(ch3);
這樣就可以了 t系列的型別和函式都是雙編譯,Unicode和MBCS的都可以用,最穩妥,所以微軟強烈推薦