Cpp - String String Copying

Introduction

strcpy_s() function copies the entire contents of one string into a designated buffer.

Demo

#include <iostream> 
#include <string.h> 

int main() /*from www .j a va  2 s  . co m*/
{ 
    char string1[] = "this is a test!"; 
    char string2[80]; 

    strcpy_s(string2, string1); 

    std::cout << "String1: " << string1 << std::endl; 
    std::cout << "String2: " << string2 << std::endl; 
    return 0; 
}

Result

A character array is created and initialized with the value of a string literal.

The strcpy() function takes two character arrays: a destination that will receive the copy and a source that will copy it.

If the source array is larger than the destination, strcpy() writes data past the end of the buffer.

strncpy() function takes a third argument that specifies the maximum number of characters to copy:

strncopy(string1, string2, 80);