Tuesday, July 14, 2009

Static cast in C++?

guys how can I use The static cast to write this C++ program:


Write a Program that prompts the user to input an integer between 0 and 35. If the number is less than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11, C for 12, . . ., and Z for 35. (Hint: Use the cast operator, static_cast%26lt;char%26gt; ( ), for numbers%26gt;=10.

Static cast in C++?
The static_cast can be used to take a data type (like integer, float, etc) and cast it (aka convert it) to another data type like making an integer into a character like you need for this example.





The trick here is that the integer 35 isn't the ascii number for Z, so you will have to do a bit of addition before converting.





For example... if you look at an ascii chart you will notice that the capital "Z" is number 90.





static_cast%26lt;char%26gt;(90) will then give you the capital Z. So what we need to do is take the difference between 90 and 35... which is 55 and add it to every number the user types in greater than or equal to 10, then convert it.





So if the user entered.... 11, we would add 55 and get 66 then go static_cast%26lt;char%26gt;(66) to get a character "B". We then print out the character to screen.





As a side note, lower case letters start at 97 for "a" and go to 122 for "z" so that offset will need to be figured out if you want to use lower case.





I will let you figure that one out.





Hope this helps you out. Enjoy!
Reply:Please make few modifications to support your needs. The lines are broken.





To contact me mail me at m_gopi_m@yahoo.co.in.





I hope this is the program you are expecting.





//program for static casting.





#include%26lt;iostream.h%26gt;


#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;





char static_cast(int);





void main()


{


int num;


char a;





clrscr();


cout%26lt;%26lt;"\n Enter a number: ";


cin%26gt;%26gt;num;





if(num%26gt;=0 %26amp;%26amp; num%26lt;=9)


{


cout%26lt;%26lt;"\n\n The given number: "%26lt;%26lt;num;


cout%26lt;%26lt;"\n\n The corresponding character: "%26lt;%26lt;num;


}


else if(num%26gt;9 %26amp;%26amp; num%26lt;36)


{


a=static_cast(num);


cout%26lt;%26lt;"\n\n The given number: "%26lt;%26lt;num;


cout%26lt;%26lt;"\n The corresponding character: "%26lt;%26lt;a;


}


else


cout%26lt;%26lt;"\n\n Cannot predict the value.";


getch();


}





char static_cast(int num)


{


int first='A'; //static casting is invoked here.


char a;


num-=10;


a=first+num;


return(a);


}


No comments:

Post a Comment