Link to home
Start Free TrialLog in
Avatar of searchsanjaysharma
searchsanjaysharma

asked on

Junk character in assigning int to char data type why?

void main()
{
         int a=5;
         char str[0];
         str[0]=a;
         cout<<str[0];
}
Doesn't print 5, why.
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Because you have assigned a binary 5 to str[0] and not the character '5'.  If you make the first assignment char a = '5'; then it should print '5'.
In declaring  
str[0]=a;
 you are saying input the character with the ASCII value of 5

If you use int
a='5';
and ouput a you will get 53 as ascii value of 5


Have a look at this ASCII table

http://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

Michael
Avatar of searchsanjaysharma
searchsanjaysharma

ASKER

I an writing a code which converts aaa to a3
Simlarly aaabbbbb as a3b5
This is why i need 5 to be appended in char array.
ASKER CERTIFIED SOLUTION
Avatar of Michael Fowler
Michael Fowler
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What is the logic behind.
It works by adding the ASCII value of char '0' to the integer digit.