How to read from stdin with fgets()?

后端 未结 5 1152
名媛妹妹
名媛妹妹 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 05:14

    If you want to concatenate the input, then replace printf("%s\n", buffer); with strcat(big_buffer, buffer);. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE]; big_buffer[0] = '\0';. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE). The modified program would look like this:

    #include 
    #include 
    
    #define BUFFERSIZE 10
    #define BIG_BUFFERSIZE 1024
    
    int main (int argc, char *argv[])
    {
        char buffer[BUFFERSIZE];
        char *big_buffer = new char[BIG_BUFFERSIZE];
        big_buffer[0] = '\0';
        printf("Enter a message: \n");
        while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
        {
            if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
            {
                strcat(big_buffer, buffer);
            }
        }
        return 0;
    }
    

提交回复
热议问题