-2

In my program, I need put a CString variable in a MessageBox. I use the following code:

messagebox("hi" + txt);

But I get the following error message:

error C2678: binary '+' : no operator found which takes a left-hand operand of type 'const char [3]' (or there is no acceptable conversion)

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Ehsan Banaei
  • 31
  • 1
  • 8

3 Answers3

0

Use format method of the CString. The Format method do thing like how printf, sprintf works.

Example

 CString str ;
 str.Format("Hi %s", txt);
Sivaraman
  • 438
  • 2
  • 9
  • Error 1 error C2664: 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [6]' to 'const wchar_t *' e:\project\visual studio 2008\projects\test2\test2\test2dlg.cpp 174 test2 – Ehsan Banaei May 22 '14 at 08:36
  • Unnecessary, you can concatenate two CString values using the binary `+` operator. You don't need Format unless you're actually doing some complex formatting. Either way, though, you will need to use wide string literals. Prefix them with an `L`. – Cody Gray - on strike May 22 '14 at 08:37
  • plz put your code @CodyGray – Ehsan Banaei May 22 '14 at 08:39
  • Cody Gray says you can use binary + with CString itself. That is CString str = _T("Hi ") + txt. @Cody Gray: When should I use L or _T? – Sivaraman May 22 '14 at 08:47
  • 1
    Prefixing with `L` makes it a wide string. Using the `_T` macro determines at compile-time, based on some preprocessor definitions, whether the literal should be a wide or narrow string. Either one is fine, but `_T` is sort of pointless now since everything is Unicode. No one cross-compiles for ANSI or MBCS. – Cody Gray - on strike May 22 '14 at 08:49
0

you can use a CString variable to format, then pass it to MessageBox.
_T() is a macro for Unicode or MBCS.
you should make sure txt is same encode as str,

CString str ;
str.Format(_T("Hi %s"), txt);

Jerry YY Rain
  • 4,134
  • 7
  • 35
  • 52
0

Use the _T macro to wrap the string literal into a CString:

messagebox(_T("hi") + txt);
Shoe
  • 74,840
  • 36
  • 166
  • 272