getchar and putchar

后端 未结 6 2120
耶瑟儿~
耶瑟儿~ 2021-02-06 14:40

My C code:

int c;
c = getchar();

while (c != EOF) {
    putchar(c);
    c = getchar();
}

Why does this program react like this on inputting

6条回答
  •  耶瑟儿~
    2021-02-06 15:00

    getchar reads the input from input stream which is available only after ENTER key is pressed. till then you see only the echoed result from the console To achieve the result you want you could use something like this

    #include 
    #include 
    #include 
    
    int getCHAR( ) {
        struct termios oldt,
                     newt;
        int            ch;
        tcgetattr( STDIN_FILENO, &oldt );
        newt = oldt;
        newt.c_lflag &= ~( ICANON | ECHO );
        tcsetattr( STDIN_FILENO, TCSANOW, &newt );
        ch = getchar();
        putchar(ch);
        tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
        return ch;
    }
    void main() {
        int c;
        c = getCHAR();
        while (c != 'b') {
            putchar(c);
            c = getCHAR();
        }
    }
    

提交回复
热议问题