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.

Note: Join free Sanfoundry classes at Telegram or Youtube
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.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.