Solution for Exercise 20-6

ex2006

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

int main()
{
    char *input1,*input2;
    char *i1,*i2;

    input1 = (char *)malloc(sizeof(char)*1024);
    input2 = (char *)malloc(sizeof(char)*1024);
    if(input1==NULL || input2==NULL)
    {
        puts("Unable to allocate buffer! Oh no!");
        exit(1);
    }

    puts("Type something long and boring:");
    fgets(input1,1023,stdin);

    puts("Copying buffer...");
    i1=input1; i2=input2;
    while(*i1 != '\n')
    {
        switch(*i1)
        {
            case 'a':
            case 'A':
            case 'e':
            case 'E':
            case 'i':
            case 'I':
            case 'o':
            case 'O':
            case 'u':
            case 'U':
                *i2++='@';
                i1++;
                break;
            default:
                *i2++=*i1++;
        }
    }
    *i2 = '\0';

    printf("Original text:\n\"%s\"\n",input1);
    printf("Duplicate text:\n\"%s\"\n",input2);

    return(0);
}

Notes

* The machine that makes this program work is the switch-case structure. Basically, I set up a condition to look for all the vowels in various case statements. If found, then the @ character is placed into the pointer i2. Also, pointer i1 must be incremented as well, to skip over the vowel, which happens at Lines 36 and 37. Otherwise, the default condition is the same as for the solution to Exercise 20-5.

* As with Exercise 20-5, Line 43 caps the second string with a null character, \0. This is required or the string would overflow when displayed at Line 46.

* Sample output: