Search This Blog

Friday, August 17, 2012

C++: The "strcat" and "strcpy" functions

Today I'm going to introduce you 2 new functions from the "string.h"  library: "strcpy" which copies the content of a string in another one and "strcat"  which concatenates 2 strings.
I can't show you the syntax of these to functions better than with an example, so let's try to solve the following problem: In the input file there are 2 strings, "x" and "y". You have to create a "z" string with the content from the "x" string, followed by the content from the "y" string and between them the word "and". After that, print on the screen the 3 strings
problem.in

apples
pears

problem.out

the x string is apples
the y string is pears
the z string is apples and pears

Here you are the source-code for the problem, using the 2 functions:
#include <string.h>
#include <stdio.h>
int main ()
{
         freopen("problem.in", "r", stdin);

         freopen("problem.out", "w", stdout);
        char x[1000],y[1000],z[1000];
        int i;

        //now we'll read the 2 strings from the input file
        gets(x);
        gets(y);

        //in the next we'll copy the string "x" in the string "z"


        strcpy(z,x);
       
        //now we'll write the "and" after the content of the string "x", from the string "z"
        strcat(z, " and ");

       //and finally add the string "y"
       strcat(z, y);

       printf("the x string is %s\nthe y string is %s\nthe z string is %s\n", x,y,z);
       return 0;
}

No comments:

Post a Comment