Why does this getchar () loop stop after entering a single character?

#include <stdio.h>

int main() {
    char read = ' ';

    while ((read = getchar()) != '\n') {
        putchar(read);
    }

    return 0;
}

My input f(it should be followed, of course). I expect it getchar()to ask for input again, but instead the program will exit. How so? How can i fix this?

+3
source share
5 answers

A terminal can sometimes be a little confusing. You must change your program to:

#include <stdio.h>

int main() {
    int read;
    while ((read = getchar()) != EOF) {
        putchar(read);
    }
    return 0;
}

, getchar EOF ( -1) . getchar int, "read" , EOF. EOF Linux ^ D, , ^ Z (?).

, .

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

, '\n'. , , enter, '\n'. , :

~$\a.out

(empty line)                    

getchar() , ,

f                   

. "F" , .

f
f~$                 

enter. "f\n". 'enter' , . f , "\n" .

. , .

+7

getchar() . , , .. , , 'Enter', , / ( stdin) to getchar(), "\n" . , , , "\n" . Facit: getchar() '\n' ( ?).

+2

f "enter", '/n'. . , , , .

+1

, , \n (), 0; , .

, -

 while ((read = getchar()) != EOF) {
        putchar(read);
    }
+1

nx Control-D, tty, , . ^ D - tty , . .

0

Source: https://habr.com/ru/post/1737339/


All Articles