Why does this C program print weird characters in output?

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

    C (and C++) interpret the while loop as:

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

    So ch gets the value 1 (for true), which is an unprintable character. You should use explicit parenthesis to fix the precedence:

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

提交回复
热议问题