Tuesday, July 28, 2009

C++ program to convert number to ascii number?

C++ program to convert number to ascii number?


i have been given an assignment to take a number input from user and convert it into its equivalent hexadecimal, octal and ascii values. i have done the hex and oct but i am sttruck on ascii can anyone plz help me....


(I NEED THE PROGRAM -%26gt; to convert user input number to ascii)


for example if the user inputs 65 the output should be A

C++ program to convert number to ascii number?
friend i have done it in C. as printf() and scanf() is allowed in C++ too it will work for you.





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


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





void main()


{


int num;


clrscr();





printf("Enter the number: ");


scanf("%d",%26amp;num);





printf("The ascii equivalent is: %c",num);


getch();


}
Reply://tested in MS VC++ 2005


#include "stdafx.h"


#include %26lt;iostream%26gt;





int _tmain(int argc, _TCHAR* argv[])


{





int nr;//integer


char c;





std::cout %26lt;%26lt; "Give me a positive number less than 255:\t" ;


std::cin %26gt;%26gt; nr;


if (nr %26gt;=1 %26amp;%26amp; nr %26lt;= 254 )


{


c = (char)nr;//character from ASCII code using type-casting


std::cout %26lt;%26lt; "ASCII from " %26lt;%26lt; nr %26lt;%26lt; " is " %26lt;%26lt; c %26lt;%26lt; "\n";


}


else


{


std::cout %26lt;%26lt; "\n\a Error!! Need a positive number less than 255 \n" ;


std::cout %26lt;%26lt; "\t\t Have a nice day !!\n";


}


return 0;


}
Reply:here is the program


main()


{


int a=65;


printf("%d \n\t %c",%26amp;a,%26amp;a);


}
Reply:If you've got the others, then just add this to them...





char myChar;


...





if (input %26lt; 256) {


myChar = input;


cout %26lt;%26lt; "Character value is: " %26lt;%26lt; myChar %26lt;%26lt; endl;


}





Of course, you could add better error checking to it
Reply:You do this by type-casting the int to a char.


e.g.. char a = (char)65;





the variable a now equals 'A'. and vice-versa. int a = (int)'A';


the -a- will now be equal to 65.

bridal flowers

No comments:

Post a Comment