Solution for Exercise 20-5

ex2005

#include <stdio.h>
#include <stdlib.h>

int main()
{
    const int bufsize = 1024;
    char *input,*output,*i,*o;

    /* allocate memory */
    input = (char *)malloc(sizeof(char)*bufsize);
    output = (char *)malloc(sizeof(char)*bufsize);
    if(input==NULL || output==NULL)
    {
        puts("Unable to allocate buffer! Oh no!");
        exit(1);
    }

    /* fetch input */
    puts("Type something long and boring:");
    fgets(input,bufsize,stdin);

    /* copy and remove the newline */
    i = input;            /* initialize the index */
    o = output;           /* initialize the index */
    while( *i != '\n' )
    {
        *o = *i;
        o++;
        i++;
    }
    *o = '\0';            /* cap the string */

    /* output the result */
    puts("You wrote:");
    printf("\"%s\"\n",output);

    return(0);
}

Output

Type something long and boring:
It was a dark and stormy night. Suddenly! The program crashed!
You wrote:
"It was a dark and stormy night. Suddenly! The program crashed!"

Notes

* I added a constant definition for the buffer size, bufsize, at Line 6.

* Line 7 declares four char pointer variables: input for the original string, output for the duplicate (minus the newline) and i and o to be used as indexes inside each buffer.

* The copying action takes place starting at Lines 23 and 24 where i and o are initialized.

* The while loop at Line 25 copies the text, setting up the condition to stop copying when the pointer *i contains the newline character.

* Line 31 is required to cap the second string with the null character, \0. Without that terminating character, the duplicate string display might include random characters. The variable o doesn't need to be incremented; after the while loop is complete, it automatically points to the end-of-string position where the null character needs to go.