By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,876 Members | 1,159 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,876 IT Pros & Developers. It's quick & easy.

simple question on type casting~

P: n/a
hi all~

i'm newbie to C++ string type and get confused when trying to convert
an int into string, i just want my cute messagebox to popup mouse
positions, here is my code:
Expand|Select|Wrap|Line Numbers
  1. MessageBox(NULL, m.lX, "Hey", MB_OK);
  2. as u guess m.lX is of type of int, any help ?
  3.  
Jan 7 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
black(flashing vampire) wrote:
hi all~

i'm newbie to C++ string type and get confused when trying to convert
an int into string, i just want my cute messagebox to popup mouse
positions, here is my code:
Expand|Select|Wrap|Line Numbers
  1.  MessageBox(NULL, m.lX, "Hey", MB_OK);
  2.  as u guess m.lX is of type of int, any help ?
  3.  


See the FAQ:
http://www.parashift.com/c++-faq-lit....html#faq-39.1

Rennie deGraaf
Jan 7 '06 #2

P: n/a
"black(flashing vampire)" <qu********@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
hi all~

i'm newbie to C++ string type and get confused when trying to convert
an int into string, i just want my cute messagebox to popup mouse
positions, here is my code:
Expand|Select|Wrap|Line Numbers
  1.  MessageBox(NULL, m.lX, "Hey", MB_OK);
  2.  as u guess m.lX is of type of int, any help ?
  3.  


The way I do it is by using string streams to convert them to std::strings.

#include <string>
#include <sstream>
template<typename T, typename F > T StrmConvert( F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}

The use of this is fairly simple. You just need to specify what you want to
convert to. The compiler figures out (somehow) what you're converting from.

std::string MyString = StrmConvert<std::string>( MyInt );

So in your specific case it would be:

MessageBox( NULL, (StrmConvert<std::string>( m.lX )).c_str(), "Hey",
MB_OK );

or if you want to see what's going on:

std::string TempStr = StrmConvert<std::string>( m.lX );
MessageBox( NULL, TempStr.c_str(), "Hey", MB_OK );

the c_str() converts a std::string into a constant c style string. So you
could copy it to a c-style string even if you wanted (but not advised).

char TempStr[100];
strcpy( TempStr, (StrmConvert<std::string>( m.lX )).c_str() );
MessageBox( NULL, TempStr, "Hey", MB_OK );

But it's best to use std::strings when you can and not convert them to
c-style strings. First off, are you positive that the number will fit in
100 bytes?
Jan 8 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.