Saturday, May 22, 2010

Please find the error c++ prog?

i just tried out this prog for a basic decln. of unions(single memory location shared by two diff. variables pref at diff. times, rite??)


can u tell me y i am not able to get my output as :


20


20 but as:


20


(and some other character-resembles a capital p)


source code:


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


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


{clrscr();


union a{


int i;


char c;


};


a b;


b.i=20;


cout%26lt;%26lt;b.i%26lt;%26lt;endl%26lt;%26lt;b.c;


getch();


}

Please find the error c++ prog?
That's because you declared b.c as a character; therefore, when you send it to 'cout', it outputs the ASCII-character equivalent of '20' which happens to be the Pilcrow Sign.





For a complete list of the ASCII Table, visit this link.





http://www.programmersheaven.com/images/...





or you could try this code sample.





-------------------------------------





for (int index = 1; index %26lt; 128; index++) {


b.i = index;





cout %26lt;%26lt; b.i %26lt;%26lt; " -- " %26lt;%26lt; b.c %26lt;%26lt; endl;


}





cout %26lt;%26lt; endl %26lt;%26lt; "Press any key to exit." %26lt;%26lt; endl;


getch();
Reply:the problem with the above code is that same memory will be used by both i and c .


but since c is a character it will take only one byte so can't expect 20 to be printed for c.
Reply:b.c = ?. Think think.





India--
Reply:The variable declared as char can not display the value of '20' as its char equivalent (ascii code) is a device control value (Device Control 4). If you try your code with a valid value e.g. 97 it would display :


97


a


on the console.


In short, the code works fine. Its just that the input value you selected can not be displayed on the console. :)


No comments:

Post a Comment