read() from stdin doesn't ignore newline

前端 未结 5 869
情话喂你
情话喂你 2020-12-10 21:01

I am using the following conditional statement to read from standard input.

if ((n = read(0,buf,sizeof(buf))) != 0)

When inputting data fro

5条回答
  •  半阙折子戏
    2020-12-10 21:25

    You have to check the buffer yourself. e.g.

    while((n = read(0,buf,sizeof(buf))) > 0) {
      if(buf[0] == '\n') // won't handle pressing 9 spaces and then enter
        continue;
      ... process input
    
    }
    

    or use e.g. fgets, and just strip off the \n

    while(fgets(buf,sizeof buf,stdin) != NULL) {
      char *ptr;
      size_t len;
    
      if((ptr = strchr(buf,'\n')) != NULL) //strip newline
        *ptr = 0; 
      len = strlen(buf);
      if(len == 0)
       continue;
      ... process input 
    }
    

提交回复
热议问题