473,973 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Formating a string using sprintf and showing it in MessageBox!

Hi everyone
I want to format a string (using sprintf) and put it in a messagebox
but however I try to do it, it doesn't seem to work.
Here is an example sample of what i try to do:

char msg[120];
string my_name = "John";

sprintf (msg, "My name is: %s ", my_name);
MessageBox(NULL , msg, NULL, MB_OK);
And this is the error I get:

error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char
[120]' to 'const unsigned short *'
Types pointed to are unrelated; conversion requires reinterpret_cas t,
C-style cast or function-style cast

I know that MessageBox wants a LPCTSTR as its second parameter. If I
use that instead (see below)...

LPCTSTR msg;
string my_name = "John";

sprintf (msg, "My name is: %s ", my_name);
MessageBox(NULL , msg, NULL, MB_OK);
....I get the following error:

error C2664: 'sprintf' : cannot convert parameter 1 from 'const
unsigned short *' to 'char *'
Types pointed to are unrelated; conversion requires reinterpret_cas t,
C-style cast or function-style cast

Seems like what ever I try to use either sprintf or MessageBox is not
happy. If I try to cast 'msg' in either sprintf or MessageBox I just
get junk as my output.
Does anyone have a suggestion how I can solve this? Please note that I
don't want to use CString since my platform does not seem to support
that. An example code of how I can solve this problem would be much
appreciated.

Thanks a lot for your help.
/Babak

Nov 17 '05 #1
12 15244
Hi babak!
I want to format a string (using sprintf) and put it in a messagebox
but however I try to do it, it doesn't seem to work.
Here is an example sample of what i try to do:

char msg[120];
string my_name = "John";

sprintf (msg, "My name is: %s ", my_name);
MessageBox(NULL , msg, NULL, MB_OK);
And this is the error I get:

error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char
[120]' to 'const unsigned short *'


You compile a UNICODE program but you heare are dealing with ANSI strings...

Change it to

<code>
ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif

TCHAR msg[120];
tstring my_name = _T("John");
__stprintf(msg, _T("My name is: %s "), (LPCTSTR) my_name);
MessageBox(NULL , msg, NULL, MB_OK);
</code>

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
Nov 17 '05 #2
> error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char
[120]' to 'const unsigned short *'
Types pointed to are unrelated; conversion requires reinterpret_cas t,
C-style cast or function-style cast Looks like the applicaiton is Unicode.
LPCTSTR msg;
string my_name = "John";

sprintf (msg, "My name is: %s ", my_name);
MessageBox(NULL , msg, NULL, MB_OK); What is "string" ?
Anyway, try:

TCHAR msg[120];
TCHAR *my_name = _T("John");

_stprintf (msg, _T("My name is: %s "), my_name);
MessageBox(NULL , msg, NULL, MB_OK);

Notes:
----------------
LPCTSTR msg;
will crash you application, because it is a non-initialized pointer.
It expands to
LPCTSTR:
LP = Long Pointer (the long is obsolete, from the old days when
Intel procesors used segmented memory)
C = const
T = generic text type
STR = string
So, this becomes:
if Non-Unicode: const char * msg;
if Unicode: const wchar_t * msg;
Generic: const TCHAR * msg;
----------------
Note _stprintf insted of sprintf and _T(".....")
If you read the doc for sprintf, you will see a table named
"Generic-Text Routine Mappings". "TCHAR.H routine" is what you
allways want.
----------------
Read about the the "Generic-Text Routine Mappings" in MSDN.
----------------
Read this blurb: http://www.mihainita.net/20050306b.shtml
Please note that I don't want to use CString since my platform does not
seem to support that.

CString is part of MFC (MFC/ATL in VC.NET). If you configure the
project to use MFC, then you will get it.

--
Mihai Nita [Microsoft MVP, Windows - SDK]
------------------------------------------
Replace _year_ with _ to get the real email
Nov 17 '05 #3
><code>
ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif

TCHAR msg[120];
tstring my_name = _T("John");
__stprintf(msg, _T("My name is: %s "), (LPCTSTR) my_name);
MessageBox(NULL , msg, NULL, MB_OK);
</code>

I did not think about std::string :-)
Jochen is right, that is what you should do.

But he is not right in double-underscore in __stprintf :-)
Correct that, and you have a running thing.

--
Mihai Nita [Microsoft MVP, Windows - SDK]
------------------------------------------
Replace _year_ with _ to get the real email
Nov 17 '05 #4
Hi Jochen
Thanks for your help. I tried what you suggested and got the following
error:

error C2440: 'type cast' : cannot convert from 'class
std::basic_stri ng<unsigned short,struct std::char_trait s<unsigned
short>,class std::allocator< unsigned short> >' to 'const unsigned short
*'
No user-defined-conversion operator available that can perform this
conversion, or the operator cannot be called

This doesn't seem like the right approach to me because to my
understanding the variable that the compiler is not happy with is 'msg'
(i.e the first parameter in sprintf and second parameter in MessageBox)
and not 'string' (which you refer to as 'tstring' in your code) that
you changed in your code. Have I missunderstood this totally?

/Babak

Nov 17 '05 #5
Hi Mihai!
__stprintf(ms g, _T("My name is: %s "), (LPCTSTR) my_name);


But he is not right in double-underscore in __stprintf :-)
Correct that, and you have a running thing.


Upps... it was a copy-and-past error...

But to be even better, he should use "_sntprintf " instead of "_stprintf" !

<code>
ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif

TCHAR msg[120];
tstring my_name = _T("John");
_sntprintf(msg, 120, _T("My name is: %s "), (LPCTSTR) my_name);
MessageBox(NULL , msg, NULL, MB_OK);
</code>
--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
Nov 17 '05 #6
Thanks for explanations in the notes to your first message, Mihai. It
is all now a little bit more clear to me. However, as I wrote in my
last message, this still does not seem to work (I used single
underscore in _sprintf). Any suggestions?

Thanks for your help.
/Babak

Nov 17 '05 #7
Hi babak!
error C2440: 'type cast' : cannot convert from 'class
std::basic_stri ng<unsigned short,struct std::char_trait s<unsigned
short>,class std::allocator< unsigned short> >' to 'const unsigned short
*'
No user-defined-conversion operator available that can perform this
conversion, or the operator cannot be called


Upps.. I forgot that the STL-(w)string class has not const-operator...

Here is a complete working example:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib ")

#include <string>

#ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif

int _tmain()
{
TCHAR msg[120];
tstring my_name = _T("John");
_sntprintf(msg, 120, _T("My name is: %s "), my_name.c_str() );
MessageBox(NULL , msg, NULL, MB_OK);
}

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
Nov 17 '05 #8
Here is a complete working example:

Again a really, really complete working example:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib ")

#include <string>

#ifdef _UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif

int _tmain()
{
TCHAR msg[120+1];
tstring my_name = _T("John");
_sntprintf(msg, 120, _T("My name is: %s "), my_name.c_str() );
msg[120] = 0;
MessageBox(NULL , msg, NULL, MB_OK);
}

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
Nov 17 '05 #9
Thanks a lot for your help. Not it seems to be working properly!

/Babak

Mihai N. skrev:
error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char
[120]' to 'const unsigned short *'
Types pointed to are unrelated; conversion requires reinterpret_cas t,
C-style cast or function-style cast

Looks like the applicaiton is Unicode.
LPCTSTR msg;
string my_name = "John";

sprintf (msg, "My name is: %s ", my_name);
MessageBox(NULL , msg, NULL, MB_OK);

What is "string" ?
Anyway, try:

TCHAR msg[120];
TCHAR *my_name = _T("John");

_stprintf (msg, _T("My name is: %s "), my_name);
MessageBox(NULL , msg, NULL, MB_OK);

Notes:
----------------
LPCTSTR msg;
will crash you application, because it is a non-initialized pointer.
It expands to
LPCTSTR:
LP = Long Pointer (the long is obsolete, from the old days when
Intel procesors used segmented memory)
C = const
T = generic text type
STR = string
So, this becomes:
if Non-Unicode: const char * msg;
if Unicode: const wchar_t * msg;
Generic: const TCHAR * msg;
----------------
Note _stprintf insted of sprintf and _T(".....")
If you read the doc for sprintf, you will see a table named
"Generic-Text Routine Mappings". "TCHAR.H routine" is what you
allways want.
----------------
Read about the the "Generic-Text Routine Mappings" in MSDN.
----------------
Read this blurb: http://www.mihainita.net/20050306b.shtml
Please note that I don't want to use CString since my platform does not
seem to support that.

CString is part of MFC (MFC/ATL in VC.NET). If you configure the
project to use MFC, then you will get it.

--
Mihai Nita [Microsoft MVP, Windows - SDK]
------------------------------------------
Replace _year_ with _ to get the real email


Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6187
by: Andrew Connell | last post by:
Having fits transforming an XML string using an XSL file. In the 1.1 version of the framework, I see that the XmlResolver is heavily used in the XslTransform class. However, that looks like I am only supposed to use that only when you have an xml ~file~... not an XML string (my XML is coming from a database field). Is there a cut & dry example out there on how to transform a simple XML string using XSL? -AC
2
4635
by: Maziar Aflatoun | last post by:
Hi guys, I'm using Windows authentication to connect to SQL Server 2000. On my computer the connection is fine. Now if I move it to a remote server, how to I hard code my Username/Password in my connection string (using Windows NT authentication and not SQL Server authentication)? Thank you Maz.
2
3914
by: Bruno | last post by:
Hello friends I'm creating one application that will send content to another app using HTTP connection. To authenticate my connection, I need to send a string with the username and password encoded using Base64. Dim username as String Dim pass as String Dim info_user as String info_user = username + ":" + pass
3
10186
by: minguskhan | last post by:
Does anyone know how to reverse a string using a loop?
2
10364
by: aurora | last post by:
I have some unicode string with some characters encode using python notation like '\n' for LF. I need to convert that to the actual LF character. There is a 'unicode_escape' codec that seems to suit my purpose. >>> encoded = u'A\\nA' >>> decoded = encoded.decode('unicode_escape') >>> print len(decoded) 3 Note that both encoded and decoded are unicode string. I'm trying to use
11
3970
by: wreckingcru | last post by:
I'm trying to tokenize a C++ string with the following code: #include <iostream> #include <stdio> #include <string> using namespace std; int main(int argc, char* argv)
7
38482
by: wenmang | last post by:
what is format for sprintf to convert long long integer (64 bits) to string?
8
1982
by: Nkhosinathie | last post by:
i'm comparing two string using the function stryncmp,but my problem is when i execute the program it doesn't give me the correct values.actually it gives me same results as the function strycmp this is the code i did. include<iostream> using namespace std; //#include<stdio.h> #include<string.h> int main() {
2
2350
by: powerfulperl | last post by:
I want to locate a string 'Local=IN' from a file and I am sure that this string is located within 100 lines(assumption) from the beginning of the file out of 5000 lines. The 100th line start with the word '--Begin'. So in order to locate the string from only 100 line, I think copying all the file content into any array is not a good idea. I want the grep command to exist in the script. I have the following code. I need this to be modified...
0
10347
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11811
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11399
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10901
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7600
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6410
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6542
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
5147
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4726
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.