Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

input - C - Reading from stdin as characters are typed

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.

I've looked into a lot of different ways, but enter has to be pressed then the input char* gets cut off at 80..

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <stdio.h>
#include <unistd.h>
#include <termios.h>
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!='
' && i < 80) r[i++] = c;
  r[i] = 0;
  tcsetattr(0,TCSANOW,&old);
  printf("Entered <%s>
",r);
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...