Copy a string using strcpy() and copy characters of one string to another using strncpy()

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Copy a string using strcpy() and copy characters of one string to another using strncpy() C functions

To show: Using strcpy() to copy a string and strncpy() to copy characters of one string to another

 

// Using strcpy()/strcpy_s()/wcscpy()/wcscpy_s()/_mbscpy_s() and strncpy()/strncpy_s()/wcsncpy()/_mbsncpy()

#include <stdio.h>

#include <string.h>

 

int main(void)

{

char x[] = "Yo! Happy Birthday to me";

char y[26], z[15];

 

printf("Using strcpy() and strncpy()\n");

printf("----------------------------\n");

printf("The string in array x is: %s\n", x);

 

// strcpy(y, x) using a secure version

strcpy_s(y, 25, x);

printf("Copy the string from x to y...\n");

printf("The string in array y is: %s\n", y);

 

// strncpy(z, x, 14); - using a secure version

strncpy_s(z, 15, x, 14);

z[14] = '\0';

printf("Only 14 characters ....\n", z);

printf("The string in array z is: %s\n", z);

return 0;

}

 

Output example:

 

Using strcpy() and strncpy()

----------------------------

The string in array x is: Yo! Happy Birthday to me

Copy the string from x to y...

The string in array y is: Yo! Happy Birthday to me

Only 14 characters ....

The string in array z is: Yo! Happy Birt

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index