Ch.11 PE 7 (ENHANCED) strncpy(s1,s2,n) copies exactly n chars from char array s2
ID: 3767299 • Letter: C
Question
Ch.11 PE 7 (ENHANCED) strncpy(s1,s2,n) copies exactly n chars from char array s2 to s1, truncating s2 if it is longer, or padding with nulls if shorter. The target string s1 may not include the null terminator if s2 was n chars or longer. The function returns a pointer to s1. Write your own version of this function, and test it with a program that prompts the user for word inputs and the number of chars to copy, until the user types quit. The test program should call strncpy() and print both strings, as in the examples below:
Explanation / Answer
#include<iostream.h>
#include<conio.h>
#include<string.h>
char* strncpy(char s1[], char s2[], int n)
{
int i;
for(i=0;i<n;i++)
{
s1[i]=s2[i];
}
return s1;
}
void main()
{
char s[20],s1[20],s2[20];
int n;
cout<<"enter word";
cin>>s2;
cout<<"Enter number";
cin>>n;
strcpy(s,strncpy(s1,s2,n));
cout<<"s1 is "<<s;
getch();
}