Why does this C program print weird characters in output?

后端 未结 3 1752
一向
一向 2021-01-12 20:52

I\'ve the following program:

#include 

int main()
{
        int ch;
        while( ch = getchar() != \'\\n\') {
                printf(\"Read         


        
3条回答
  •  北海茫月
    2021-01-12 21:32

    You need to place parenthesis as:

    while( (ch = getchar()) != '\n')
    

    Precedence of != is greater than that of =

    while( ch = getchar() != '\n')
    

    is same as:

    while( ch = (getchar() != '\n') )
    

    which reads a char compares it with newline and then assigns the result of comparison to ch. Now the result of comparison is 0 (when newline is entered) or 1 (when anything else is entered)

    The weird char you're seeing is the control char with value 1, there is no printable symbol for ASCII 1, so I guess its the shell that prints the weird char with value 0001 in it.

    You can confirm it by piping your program output to octal dump (od) :

    $ echo 'a' | ./a.out | od -bc         # user entered 'a'
    0000000 122 145 141 144 040 001 012
              R   e   a   d     001  \n
    here you go  ----------------^
    
    
    $ echo '\n' | ./a.out | od -bc        # user entered '\n'
    0000000
    

    GCC when used with -Wall warns you as:

    warning: suggest parentheses around assignment used as truth value
    

提交回复
热议问题