This question already has an answer here:
I've created a pointer pointing to a couple of chars but after assigning it to some value and then trying to print it on the MessageBox and compiling it is giving me some errors.My code is given below:
#include <Windows.h>
#include <string.h>
#include <iostream>
using namespace std;
void main()
{
char buff[100];
string id = "ST_5";
sprintf_s(buff, "id: %s", id.c_str());
MessageBox(NULL, buff,L"User-id", MB_OK);
}
Please help me in finding the problem in this code, Thanks.
My compiler's output: c:\users\zafri\documents\visual studio 2012\projects\test3\test3\test3.cpp(19): error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char [100]' to 'LPCWSTR' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
You should use wchar_t type for all variables, objects and functions, this code works:
The function swprintf_s() is the wchar_t/safe version of the sprintf/snprintf
Ciao
You should read the compiler error messages.
The second and third arguments to
MessageBox
have to have the same type. Either you callMessageBoxA
with twochar *
, or you callMessageBoxW
with twowchar_t *
.One fix for your code would be to do
MessageBoxA(NULL, buff, "User-id", MB_OK)
.You are using
sprintf_s
incorrectly too, please read its documentation. IMHO it would be better to use the standard functionsnprintf
:Note that you could do away with
buff
entirely and write:For the second argument of
MessageBox
you usechar
s, while for the third one you usewchar_t
s. This is wrong. If you build not for UNICODE, removeL
fromL"User-id"
so it becomeschar
array.