This is a C++ Program to Implement strncpy() Function.
The program takes a string and copies first ‘n’ characters into another string using the function strncpy().
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.
Here is the source code of C++ Program to Implement strncpy() Function. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
char str[50], cpy[50];
int n;
cout << "Enter a string : ";
gets(str);
cout << "Enter number of characters to be copied : ";
cin >> n;
strncpy(cpy, str, n);
cout << "Copied string : " << cpy;
return 0;
}
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.
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 for C++ Internship
- Practice Programming MCQs
- Practice Computer Science MCQs
- Check Computer Science Books
- Check C++ Books