Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 382
  • Last Modified:

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.
0
searchsanjaysharma
Asked:
searchsanjaysharma
  • 3
  • 2
1 Solution
 
Dave BaldwinFixer of ProblemsCommented:
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'.
0
 
Michael FowlerSolutions ConsultantCommented:
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
0
 
searchsanjaysharmaAuthor Commented:
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.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Michael FowlerSolutions ConsultantCommented:
To convert the int to a char you can use

str[0]='0' + a;

Michael
0
 
searchsanjaysharmaAuthor Commented:
What is the logic behind.
0
 
Michael FowlerSolutions ConsultantCommented:
It works by adding the ASCII value of char '0' to the integer digit.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now