C - Reading from stdin as characters are typed

我怕爱的太早我们不能终老 提交于 2019-12-02 03:48:35

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!='\n' && i < 80) r[i++] = c;
  r[i] = 0;
  tcsetattr(0,TCSANOW,&old);
  printf("Entered <%s>\n",r);
  return 0;
}
#include<stdio.h>
...
int count=0;
char buffer[81];
int ch=getchar();
while(count<80&&ch!='\n'&&ch!='\r'&&ch!=EOF){
    buffer[count]=ch;
    count=count+1;
    ch=getchar();
}
buffer[count]='\0';

Once you have buffer as a string, make sure you digest the rest of the line of input to get the input stream ready for its next use.

This can be done by the following code (taken from the scanf section of this document):

scanf("%*[^\n]");   /* Skip to the End of the Line */
scanf("%*1[\n]");   /* Skip One Newline */
#include <stdio>
...
char buf[80];
int i;
for (i = 0; i < sizeof(buf) - 1; i++)
{
    int c = getchar();
    if ( (c == '\n') || (c == EOF) )
    {
        buf[i] = '\0';
        break;
    }
    buf[i] = c;
}
buf[sizeof(buf] - 1] = '\0';
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!