【问题标题】:Getting an unexpected error in my MFC application在我的 MFC 应用程序中出现意外错误
【发布时间】:2015-08-17 06:02:57
【问题描述】:

我正在尝试逐字符访问CString 的元素。
我在以下代码行中遇到错误:

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

错误:

“错误 1 ​​错误 C2664: 'int CWnd::MessageBoxW(LPCTSTR,LPCTSTR,UINT)' : 无法将参数 1 从“wchar_t”转换为“LPCTSTR”” "MessageBox(lstring[0]);"

【问题讨论】:

    标签: c++ visual-c++ mfc c-strings


    【解决方案1】:

    如果你只想打印MessageBox 中的第一个字符,那么不要期望它会从LPCTSTR -> LPCWSTR (Unicode) -> const WCHAR* 转换为@987654330 @

    打印整个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());
    

    【讨论】:

    • 我只使用 index 作为 0 来测试是否能够访问数据,,,我想对该 lstring 中存在的数据进行操作,然后稍后在我的 gui 中以 cstatic 显示它跨度>
    • @user78766 您在问题中没有提到任何内容。如果CString 不是.IsEmpty,您可以访问数据。另见CString::operator[ ]
    • 是的,这就是重点,一个意外错误,,,,我已经尝试使用 [] 和 GetAt 两个函数返回相同的错误,,,,我什至尝试通过查看 msdn 中的示例来初始化字符串,,, 即使那样我也会遇到同样的错误,我认为代码似乎很好,,还有其他问题!
    • @user78766 没有意外错误。您的问题中的错误是预期的。如果MessageBox 需要一个数组或一个指针,那么单个字符将不会这样做。请仔细查看MessageBox 接受的参数。 wchar_t* 不等于 wchar_t
    猜你喜欢
    • 2012-06-12
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多