2015-08-17 34 views
-3

我試圖按字符訪問CString的元素。
我在下面的代碼行收到一個錯誤:在我的MFC應用程序中獲取意外錯誤

void CTOTALTIMECALCDlg::OnBnClickedOk() 
{ 
    // TODO: Add your control notification handler code here 
    CString lstring; 
    m_Timeget.GetWindowText(lstring); 
    MessageBox(lstring[0]); 
    CDialogEx::OnOK(); 
} 

錯誤:

"Error 1 error C2664: 'int CWnd::MessageBoxW(LPCTSTR,LPCTSTR,UINT)' : cannot convert argument 1 from 'wchar_t' to 'LPCTSTR'" at line "MessageBox(lstring[0]);"

回答

2

如果你只想打印第一個字符在MessageBox,那就不要期望它從LPCTSTR - >LPCWSTR(Unicode) - >const WCHAR*wchar_t

打印整個CString,或正確打印第一個字符。

void CTOTALTIMECALCDlg::OnBnClickedOk() 
{ 
    // TODO: Add your control notification handler code here 
    CString lstring; 
    m_Timeget.GetWindowText(lstring); 
    if (!lstring.IsEmpty()) 
     MessageBox(lstring.Left(1)); 
    CDialogEx::OnOK(); 
} 

MessageBox接受LPCTSTR作爲參數。
LPCTSTR在Unicode設置中解析爲const wchar_t*
CString::operator[ ]返回一個TCHAR,它是Unicode中的wchar_t
CString::operator LPCTSTR()請參見下面的代碼

//You are doing this: 
MessageBox(wchar_t); 
//It wants this: 
MessageBox(wchar_t*); 
//CString::Left will return a new CString 
MessageBox(CString::Left . CString::operator LPCTSTR()); 
+0

我只是用指數爲0,測試時能夠訪問的數據是否,,,我想這樣做存在於lstring上的數據業務,後來在靜態控件在以後顯示它在我的gui – Lokanath

+1

@ user78766你沒有提到你的問題。如果'CString'不是['.IsEmpty'](https://msdn.microsoft.com/en-us/library/aa300475%28v=vs.60%29.aspx),則可以訪問數據。另請參閱['CString :: operator []'](https://msdn.microsoft.com/en-us/library/aa300563%28v=vs.60%29.aspx) – Blacktempel

+0

Ya是點,意外錯誤,,,,我已經嘗試使用[]和GetAt這兩個函數返回相同的錯誤,,,,,我甚至嘗試初始化字符串通過看到一個例子從MSDN ,,,即使那時得到相同的錯誤,因爲我看到它的代碼似乎沒事,其他的錯誤! – Lokanath

相關問題