simple question on type casting~

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • black(flashing vampire)

    #1

    simple question on type casting~

    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 ?
  • Rennie deGraaf

    #2
    Re: simple question on type casting~

    black(flashing vampire) wrote:[color=blue]
    > 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 ?
    >
    >[/color]

    See the FAQ:


    Rennie deGraaf

    Comment

    • Jim Langston

      #3
      Re: simple question on type casting~

      "black(flas hing vampire)" <quiteblack@gma il.com> wrote in message
      news:1136563620 .120350.103500@ g49g2000cwa.goo glegroups.com.. .[color=blue]
      > 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 ?
      >
      [/color]

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

      #include <string>
      #include <sstream>
      template<typena me T, typename F > T StrmConvert( F from )
      {
      std::stringstre am 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<st d::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<st d::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?


      Comment

      Working...