type casting / conversion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • askalottaqs
    New Member
    • Jun 2007
    • 75

    type casting / conversion

    i need someone to explain in the most primitive way possible, how to cast or convert between types, whats the difference between them, when do i use which, and why do i keep getting the cannot convert from type to type, and how would i do it optimally,

    i mean all i need is standard cionversions between string, char, char array, float, double, etc, but i keep getting errors its driving me crazy!

    thanks in advance,
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    I assume you are using C++ (seems a bit obvious now, but you should mention what language you use). There's five different casting methods available to you. The first is the old C style casts, which you should avoid using. The other four are C++ style casts, which you should use. I won't bother to tell you what they are as this is simply a matter of googling and reading information on your own.

    In fact, your entire question is really asking us to talk about the topic of casting. That's no longer a question. It's as meaningful a question as "what are C++ strings and tell me everything about them". Read up about C++ casting on Google. Or a good book like C++ Primer by Lippman.

    Remember that casting does not involve any logic. Casting a string to an int does not mean you get a conversion from a string to an int. Casting is a way of overriding the compiler. You effectively say, hey I know what I'm doing here, treat this variable like another. Whether it is meaningful or not is unknown. It's up to you to know what you're doing.

    Comment

    • askalottaqs
      New Member
      • Jun 2007
      • 75

      #3
      sorry for the unprofessional way i asked the question, but the problem is i have read a lot about casting, i know how it works and what it does, but i keep getting errors, i might be having some kind of a block, but im just not getting it, if i may state the example im in at the moment that giving me the errors,

      i have a *char coming from the strtok function, which i need to pass as an argument for a method in Maya's API, as a double


      1>d:\maya work\api projects (c++)\retrieveg eocmd\retrieveg eocmd\retrieveg eocmdcmd.cpp(16 4) : error C2440: 'static_cast' : cannot convert from 'char *' to 'double'

      i tried every way of casting, and its not working,

      thanks again for your time

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Originally posted by askalottaqs
        i have a *char coming from the strtok function, which i need to pass as an argument for a method in Maya's API, as a double


        1>d:\maya work\api projects (c++)\retrieveg eocmd\retrieveg eocmd\retrieveg eocmdcmd.cpp(16 4) : error C2440: 'static_cast' : cannot convert from 'char *' to 'double'
        This is what oler1s was talking about, your first question was very generic and hard to answer, this however is quite specific (it is a single problem) and we can answer it (although posting the code lines that produce the error as well would have been better).


        OK the short answer is that the compiler just can not cast between char * and double. They are incompatible types, the compiler just does not know how the treat the bits in the pointer as a double value.

        However I think you are using the wrong approach to your problem. I am guessing you have a string of characters that represent a double value and you want to get that value in a variable of type double.

        Casting is not the way to do this, casting is for use between variables of similar type so you can cast between all the numerical types (char, int, long, float double etc.) and you can cast between some pointer types e.g. any pointer casts to void *, you can cast pointers up and down class hierarchys.

        You need to convert a character string (array of chars) into a double. In C++ the easiest way to do this is to import your array of chars into a stingstream type variable and the export them out as a double

        [code=cpp]
        #include <string>
        #include <iostream>
        #include <sstream>

        using namespace std;

        /* console cpp file */
        int main()
        {
        char data [] = "1234.5";
        double result;

        stringstream converter(data) ;

        converter >> result;

        cout << result << endl;

        return 0;
        }[/code]

        Comment

        • askalottaqs
          New Member
          • Jun 2007
          • 75

          #5
          cant thank you enough Sir! ::bow::

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            To askalottaqs:

            If you want a real earful about casting in C++, post again.

            Comment

            • askalottaqs
              New Member
              • Jun 2007
              • 75

              #7
              if it isnt too much trouble! wld love to, :D thnx

              Comment

              • weaknessforcats
                Recognized Expert Expert
                • Mar 2007
                • 9214

                #8
                Start with this:
                Originally posted by weaknessforcats
                int main()
                {
                const int Value = 10;

                //TODO: Change Value to 20

                }
                But when you:
                Originally posted by weaknessforcats
                int main()
                {
                const int Value = 10;

                //TODO: Change Value to 20

                Value = 20;

                }
                it won't compile because Value is a constant. So you get sneaky:
                Originally posted by weaknessforcats
                int main()
                {
                const int Value = 10;

                //TODO: Change Value to 20

                int* ptr = &Value;
                *ptr = 20;

                }
                but it still won't compile because ptr is a pointer to an int but &Value is the address of a constant int. If the compiler allows the assignment, then the fear is you will change the Value to something else. Hence, the compiler error.

                But you persist.
                Originally posted by weaknessforcats
                int main()
                {
                const int Value = 10;

                //TODO: Change Value to 20

                int* ptr = (int*)&Value;
                *ptr = 20;

                }
                Now it compiles because you lied to the compiler. Now you decided to display the Value and its address on the monitor:
                Originally posted by weaknessforcats
                int main()
                {
                const int Value = 10;

                //TODO: Change Value to 20

                int* ptr = (int*)&Value;
                *ptr = 20;

                cout << "Value: " << Value << '\n'
                << "Value using ptr: " << *ptr << '\n'
                << "&Value: " << &Value << '\n'
                << "ptr: " << ptr << endl;


                }
                On my system, I get:
                [code=c]
                Value: 10
                Value using ptr: 20
                &Value: 0013FF4C
                ptr: 0013FF4C
                [/code]

                And you can see the 10 and the 20 are in the same memory location!

                So now the part of your program that uses Value operates on 10 and the part that uses ptr operates on 20.

                You see, the compiler never did change the const int. Instead, it made a copy for you to fiddle with. But when asked for the address, the compiled code reports the address of the original variable.

                All casting involves the making of a copy of the object of the cast. You can fill your program with these hidden copies that are never seen yet your code depends on them.

                This is the first in a long series of disasters caused by casting.

                Comment

                • askalottaqs
                  New Member
                  • Jun 2007
                  • 75

                  #9
                  thank u for your extensive example, pretty confusing but i guess i got the point,

                  and sorry for being too persistant, but i need to ask something, if u say that type casting can be disastrous what should i be using instead?

                  Comment

                  • oler1s
                    Recognized Expert Contributor
                    • Aug 2007
                    • 671

                    #10
                    and sorry for being too persistant, but i need to ask something, if u say that type casting can be disastrous what should i be using instead?
                    Well, here's a question in response. Had you not read this thread, what would you be using casting for?

                    I've seen casting misused by beginners, in commonly two ways.

                    The first is to do conversions. If you read this thread, you understand then that casting does not involve conversion. It is a tool at your disposal, to force the compiler to treat one variable type as another. C++ is a powerful, systems level language and you can therefore do so if you wish. Casting has its uses. One day you will reach a level when you will learn those underlying mechanics and will rely on casts. And it will have nothing to do with conversions.

                    The other way casting is commonly misused is beginners try to make their code compile. They find that somewhere, a variable needs to be of another type. They find that the compiler says x needs to be a char**. And they say, well, OK, let's cast x as a char**. Do you see the inherent problem in this?

                    Comment

                    • weaknessforcats
                      Recognized Expert Expert
                      • Mar 2007
                      • 9214

                      #11
                      Originally posted by askalottaqs
                      and sorry for being too persistant, but i need to ask something, if u say that type casting can be disastrous what should i be using instead?
                      To answer this you need to be clear on two things:
                      1) A cast is forcing one type to be another type over the compiler's objections.
                      2) A conversion is a orderly construction of using an object of another type.

                      With that in mind, C++ has conversion constructors. These are constrcutors that have only one argument. The object being constrcuted is a conversion of the object used as the argument:
                      [code=cpp]
                      class Date
                      {
                      public:
                      //Conversion constructors
                      Date(string str); //convert a string to a Date
                      Date(char* str); //convert a C-string to a Date
                      Date(int arg); //conver an int to a Date
                      };
                      [/code]

                      These constructors will convert these types to a Date where no cast on earth will do it.

                      So, the conversion constructor converts and object of some type to the class type.

                      To go the other way, you use conversion operators. A conversion operator is a member function that converts the class type to the type of the conversion operator:

                      [code=cpp]
                      class Date
                      {
                      public:
                      //Conversion constructors
                      Date(string str); //convert a string to a Date
                      Date(char* str); //convert a C-string to a Date
                      Date(int arg); //conver an int to a Date

                      //Conversion operators
                      operator string(); //convert a Date to a string object
                      operator char*(); //convert a Date to a C-string
                      operator int(); //convert a Date to an int
                      };
                      [/code]

                      These conversion operators allow a Date object to become another type.
                      Again, these functions convert the Date into the type of the operator function using code you write. So, this is not forcing anything.

                      A conversion operator can convert objects to another type when no cast can do it.

                      Anytime you cast in C++ a read flag should appear before your eyes with the words Wrong Way on it.

                      Now, there are times you need to cast:
                      1) working with relic C functions that have void* arguments
                      2) maybe doing file I/O (but maybe not)
                      3) maybe writing a template

                      Comment

                      Working...