CrazyEngineers
  • Vicky One
    Vicky One

    MemberOct 17, 2013

    Why the answer is -47 ?

    I have written a simple code beacuse i have two strings, one is hard coded and the sum of whose adjacent membrs is to be stored in the other string.but the answer of first two indexes of string 1 is different as following:
    #include
    #include
    #include
    int main()
    {
    char string1[]="011100011";
    char string2[9];
    cout<This code gives a symile face instead of 1.


    while the following code gives 1, why?
    #include
    #include
    #include
    int main()
    {
    char string1[]="011100011";
    char string2[9];
    cout<The problem can be solved by 2nd code but what is the true logic behind, can u explain........???


    The third code gives -47....
    #include
    #include
    #include
    int main()
    {
    char string1[]="011100011";
    char string2[9];
    cout<???
                        
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • KenJackson

    MemberOct 20, 2013

    Vicky One
    This code gives a symile face instead of 1.
    This is one of my pet peeves with cout and one of the reasons I prefer to stick with the excellent printf family of functions.

    The examples don't take into account that characters '0' and '1' have binary (ASCII) values of 48 and 49. So after the math ('0' - '0' + '1' - '0'), variable string2[0] contains a binary 1, not character '1'.

    The problem with cout is that it blindly obeys the type. Even though you wanted it to print an integer value, it was given a character type so it tried to print a character type. A binary one is often displayed as a smiley face--that's not ASCII but #-Link-Snipped-#.

    One way to handle this is to cast the character as an int:
    cout << (int)string2[0];
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register