Tuesday 11 June 2013

Program to put quotation marks on an input string

Repetition is the key to familiarity. I am still writing programs that deal with passing address of strings and manipulating them.

Here is a program that adds quotes to a string input by the user. We can simply do this by:

printf("\"%s\""arr1);

This program is a more complicated way of doing it, written as an exercise, and besides now the string in memory holds the input with quotes in them. Makes me feel like I'm putting the "s into the computer memory with tweezers or something. Heh!

#include <stdio.h>

void passed(char *x,char *y);   //PASS THE VALUE AT ADDRESS X AND Y

main()
{
    char arr1[500],arr2[500];   //both arrays have 500 blocks each set for them.

    printf("Enter a string: "); //ask for and get user string into arr1
    gets(arr1);

    passed(arr1,arr2);              //send THE ADDRESS OF THE FIRST MEMORY BLOCKS to passed
    
    printf("Here is the original string:\n%s\n",arr1);

    printf("Here is the copied string:\n%s",arr2);  //arr1 is unchanged and still contains the original input
                                                    //arr2 has quotation marks on the original string
}

void passed(char *x,char *y)
{
    *y='"'; //assign a quotation mark to the FIRST MEMORY BLOCK
    y++;    //go on to the next block
    while(*x!='\0')     //while the memoryblock does not contain \0 (NULL- which means the end of the string)
    {
        *y=*x;          //the value at *x is copied to *y.
        x++;            //next memory block
        y++;            //next memory block
    }
    *y='"';     //the entire string has been copied from arr1 (passed as a pointer *x) into arr2
                //put a " at the ending
    y++;        //next memory block
    *y='\0';    //the \0 (NULL) character is assigned here to let the program recognize the end of the string.
}

No comments:

Post a Comment