strcpy() function in C++

In this guide, you will learn what is strcpy() function is in C++ programming and how to use it with an example.

1. strcpy() Function Overview

The strcpy() function in C++ is used to copy the contents of one string to another. It's a part of the C++ <cstring> header. This function is essential when you need to duplicate or move string data from one memory location to another.

Signature:

char* strcpy(char* destination, const char* source);

Parameters:

- destination: Pointer to the destination array where the content is to be copied.

- source: String to be copied.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    char source[] = "C++ Programming";
    char destination[50];

    // Using strcpy to copy source to destination
    strcpy(destination, source);

    std::cout << "Copied string: " << destination;
    return 0;
}

Output:

Copied string: C++ Programming

3. Explanation

In the provided source code:

1. We include the necessary header files: <iostream> for input/output operations and <cstring> for strcpy().

2. Two character arrays, source and destination, are defined. The source array is initialized with a string.

3. The strcpy() function is used to copy the contents of source to destination.

4. The copied string in destination is then printed to the screen.


Comments