Using strcpy and strncpy to copy string - C++ Data Type

C++ examples for Data Type:char array

Description

Using strcpy and strncpy to copy string

Demo Code

#include <iostream> 
#include <cstring>
using namespace std; 

int main() //from   w  w  w  . ja v a 2  s. c  om
{ 
    char x[] = "this is a test test test";
    char y[ 25 ]; 
    char z[ 15 ]; 

    strcpy( y, x ); // copy contents of x into y 

    cout << "The string in array x is: " << x << "\nThe string in array y is: " << y << '\n'; 

    // copy first 14 characters of x into z 
    strncpy( z, x, 14 ); // does not copy null character 
    z[ 14 ] = '\0'; // append '\0' to z's contents 

    cout << "The string in array z is: " << z << endl; 
}

Result


Related Tutorials