How to read from stdin with fgets()?

后端 未结 5 1151
名媛妹妹
名媛妹妹 2020-11-29 04:44

I\'ve written the following code to read a line from a terminal window, the problem is the code gets stuck in an infinite loop. The line/sentence is of undefined length, th

5条回答
  •  感动是毒
    2020-11-29 04:56

    here a concatenation solution:

    #include 
    #include 
    #include 
    #define BUFFERSIZE 10
    
    int main() {
      char *text = calloc(1,1), buffer[BUFFERSIZE];
      printf("Enter a message: \n");
      while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
      {
        text = realloc( text, strlen(text)+1+strlen(buffer) );
        if( !text ) ... /* error handling */
        strcat( text, buffer ); /* note a '\n' is appended here everytime */
        printf("%s\n", buffer);
      }
      printf("\ntext:\n%s",text);
      return 0;
    }
    

提交回复
热议问题