Users Online

· Guests Online: 94

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Implement strncpy() Function

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.

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

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.20 seconds
10,832,193 unique visits