user2726531
user2726531

Reputation: 37

c++ variable declaration syntax

When I take something as simple as this:

char text1[] = "hello world";
MessageBox(NULL, text1, NULL, NULL);

I get this error:

Error   1   error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char [12]' to 'LPCWSTR'   

Upvotes: 0

Views: 239

Answers (4)

Jerry Coffin
Jerry Coffin

Reputation: 490018

You have two basic problems. First, a char can only hold one character, not a string of characters. Second, you have a "narrow" character string literal, but you're (apparently) using a Unicode build of your application, in which MessageBox expects to receive a wide character string. You want either:

wchar_t text1[] = L"hello world";

or:

wchar_t const *text1 = L"hello world";

or (most often):

std::wstring text1(L"hello world");

...but note that an std::wstring can't be passed directly to Messagebox. You'd need to either pass text1.c_str() when you call MessageBox, or else write a small wrapper for MessageBox that accepted a (reference to) a std::wstring, something like:

void message_box(std::wstring const &msg) {
     MessageBox(NULL, msg.c_str(), NULL, MB_OK);
}

Upvotes: 4

P0W
P0W

Reputation: 47784

char only hold one character, not an array of characters.

So just use a pointer to constant string of Unicode characters.

LPCWSTR text1 = L"hello world";

Upvotes: 0

JNL
JNL

Reputation: 4703

char is a single character, not a String.

You need Unicode, you can use TCHAR;

TCHAR[] text = _T("Hello World.");
MessageBox(NULL, text, NULL, NULL);

Upvotes: 0

JaredPar
JaredPar

Reputation: 754525

A string literal in C/C++ is not a char but a collection of char values. The idiomatic way of declaring this is

const char* text1 = "hello world";

Upvotes: 0

Related Questions