Packing two characters to an integer

后端 未结 2 914
耶瑟儿~
耶瑟儿~ 2021-01-23 14:53

I have written a code to pack two characters to an integer; which should output in both decimal and binary formats.

The code compiled successfully, but the problem is,

2条回答
  •  孤独总比滥情好
    2021-01-23 15:45

    scanf("%c",&character2);
    

    picks up the newline character that was left on the input stream when you read the first character.

    Change it to:

    scanf(" %c",&character2);
    

    Update In response to the comment by @user3615120

    Let's say you entered a and Enter when you wanted to read the first character. At that time, the input stream has two characters in it: 'a' and '\n'. When the line

    scanf("%c",&character1);
    

    gets executed, 'a' is read and stored in character1. The '\n' is still left in the input stream.

    When

    scanf("%c",&character2);
    

    is executed, the '\n' is read and stored in character2. When you change that line to

    scanf(" %c",&character2);
    

    the white spaces that are left in the stream is discarded. The first non-whitespace character is read and stored in character2.

提交回复
热议问题