VC++ (VS2013)里面char和LPTSTR的转换问题

孙鑫vc++第七课在VS2013里面写如下代码,实现两个数的相加并且显示结果:
    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还是有些不一样的。

参考资料:http://topic.csdn.net/u/20090506/17/d7e4b312-ba8a-4611-b94b-59c5c7a96aea.html

解决方案:

char 改成TCHAR
atoi 改成 _ttoi
itoa 改成 _itot

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

像上面这样写后在VS2013里还是会报一个安全错误

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

这样就可以了

VC++ (VS2013)里面char和LPTSTR的转换问题_第1张图片

t系列的类型和函数都是双编译,Unicode和MBCS的都可以用,最稳妥,所以微软强烈推荐












你可能感兴趣的:(VS2013,LPTSTR,C2664)