Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CSE 202 Lab 3 4. strncpy() copies the first n characters of source to target and

ID: 3716064 • Letter: C

Question

CSE 202 Lab 3 4. strncpy() copies the first n characters of source to target and terminates it with the null character. If source is shorter than n characters, it works just like strcpy(). Note target char-array must have enough space to fit the source strcat ) concatenates source to end of target. Note target char-array must have enough space to fit both source and target. Here are strncpy() and strcat() function:s void strncpy (char t[], const char s[], const unsigned int n) unsigned int i; for (i- ; in and s[i]; i++) void strcat(char t[], const char s[]) unsigned int i; for (i 0; t[i]; i++); // or i -strlen(t); strcpy (tti, s); Modify your main) to test correctness of both functions Give the pointer version of both functions Test correctness of the new versions. Simply recompile and run! :28 AM Type here to search 4/25/2018

Explanation / Answer

strncpy() function using pointers -

#include<iostream>
using namespace std;
void strncpy(char *t, const char *s, const unsigned int n)
{
unsigned int i ;
for(i=0;(i<n);i++)
{
*t = *s;
s++;
t++;
}
*t = '';
}
main()
{
char s[100], t[100] ;
int n ;

cout<<"Enter s string"<<endl;
cin>>s;
cout<<"Enter n"<<endl;
cin>>n;
strncpy(t, s, n);

cout<<"Final string is "<<t<<endl;

return 0;
}

Output -

./a.out
Enter s string
Jyotiprakash
Enter n
6
Final string is Jyotip

./a.out
Enter s string
jyoti
Enter n
10
Final string is jyoti

For strcat() function -

#include<iostream>
using namespace std;
void strcat(char *t, const char *s)
{
unsigned int i ;
while(*t)
{
t++;
}
while(*s)
{
*t=*s;
t++;
s++;
}
*t = '';
}
main()
{
char s[100], t[100] ;
int n ;

cout<<"Enter string t"<<endl;
cin>>t;
cout<<"Enter string s"<<endl;
cin>>s;
strcat(t, s);

cout<<"Final string is "<<t<<endl;

return 0;
}

Output -

./a.out
Enter string t
jyoti
Enter string s
sahoo
Final string is jyotisahoo