C++ Program to Implement strncpy() Function

This is a C++ Program to Implement strncpy() Function.

Problem Description

The program takes a string and copies first ‘n’ characters into another string using the function strncpy().

Problem Solution

1. The program takes a string.
2. The number of characters to copied is taken.
3. Using the string function strcpy(), first n characters are copied into another string.
4. The result is printed.
5. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Implement strncpy() Function. The program output is shown below.

  1. #include<iostream>
  2. using namespace std;
  3. int main ()
  4. {
  5.     char str[50], cpy[50];
  6.     int n;
  7.     cout << "Enter a string : ";
  8.     gets(str);
  9.     cout << "Enter number of characters to be copied : ";
  10.     cin >> n;
  11.     strncpy(cpy, str, n);
  12.     cout << "Copied string : " << cpy;
  13.     return 0;
  14. }
Program Explanation

1. The user is asked to enter a string and stored in the character variable ‘str’.
2. Number of characters to be copied is asked to enter. It is stored in the variable ‘n’.
3. Using strncpy(), first ‘n’ characters from str are copied into a new string ‘cpy’.
4. The copied string is then printed.

advertisement
Runtime Test Cases
Case 1 :
Enter a string : Hello
Enter number of strings to be copied : 4
Copied string : Hell
 
Case 2 :
Enter a string : 25 + 12 = 37
Enter number of strings to be copied : 7
Copied string : 25 + 12
 
Case 3 :
Enter a string : fresh&fresh
Enter number of strings to be copied : 5
Copied string : fresh

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

👉 Apply Now for Free C Certification - December 2025

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.