Why does this C program print weird characters in output?

后端 未结 3 1781
一向
一向 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:36

    ch = getchar() != '\n'
    

    Writing this will cause unexpected behavior depending on the languages operator precedence. In C = is evaluated after != so ch will be true or false. Try:

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

提交回复
热议问题