‘ ‘, ‘\n’ , scanf() and output screen

First the issue: the default tty mode is canonical, meaning input is made available line by line (see man termios)

Once you fix that, you can use getchar() or read() to get one character at a time. The tty setting, example straight out of the man page of termios .

#include <stdio.h>
#include <termios.h>




int ttySetNoncanonical(int fd, struct termios *prev)
{
    struct termios t;
    if (tcgetattr(fd, &t) == -1)
        return -1;
    if (prev != NULL)
        *prev = t;
    t.c_lflag &= ~ (ICANON);
    t.c_cc[VMIN] = 1; // 1-char at a go
    t.c_cc[VTIME] = 0; // blocking mode
    if (tcsetattr(fd, TCSAFLUSH, &t) == -1)
        return -1;
    return 0;
}



void main(void) {
    printf ("\nType the string without spaces\n");
    ttySetNoncanonical(0,NULL); // set to non-canonical mode
    char X[1000];
    int m, ec=0;
    int i;
    X[0] = 0;
    for (i=0;i<1000;i++) {
        //ec = read(0,X+i,1); // read one char at a time
        m = getchar();
        if(m == EOF || m==' ' || m=='\n') {
            X[i] = 0;
            break;
        }
        X[i] = m;
    }
    printf("You entered %s. Bye.\n\n", X);
}

HTH. You might want to check the boundary condition, in case your user typed in 1000 characters. It works for me on a GNU Linux.

Leave a Comment