simple question on type casting~

  • Thread starter black(flashing vampire)
  • Start date
B

black(flashing vampire)

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:
Code:
MessageBox(NULL, m.lX, "Hey", MB_OK);
as u guess m.lX is of type of int, any help ?
 
J

Jim Langston

black(flashing vampire) said:
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:
Code:
MessageBox(NULL, m.lX, "Hey", MB_OK);
as u guess m.lX is of type of int, any help ?

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top