C - Reading from stdin as characters are typed

前端 未结 3 1347
醉梦人生
醉梦人生 2021-01-27 01:54

How do I fill an 80-character buffer with characters as they are being entered or until the carriage return key is pressed, or the buffer is full, whichever occurs first.

<
3条回答
  •  Happy的楠姐
    2021-01-27 02:30

    If you really want the characters "as they are entered", you cannot use C io. You have to do it the unix way. (or windows way)

    #include 
    #include 
    #include 
    int main() {
      char r[81];
      int i;
      struct termios old,new;
      char c;
      tcgetattr(0,&old);
      new = old;
      new.c_lflag&=~ICANON;
      tcsetattr(0,TCSANOW,&new);
      i = 0;
      while (read(0,&c,1) && c!='\n' && i < 80) r[i++] = c;
      r[i] = 0;
      tcsetattr(0,TCSANOW,&old);
      printf("Entered <%s>\n",r);
      return 0;
    }
    

提交回复
热议问题