In the book it says the following code causes the new value of s to contain “Say Hi”, this string also displays onscreen because it is the value that strncpy() returns.
But rather it looks to me like it overwrites the first 2 chars in s with the first 2 chars in t, hence the y and the space after it showing up in the output.
Is the author of the book that I am reading wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <cstring>
usingnamespace std;
int main(void)
{
char s[7]= "Say ";
char t[]="Hi";
cout << strncpy(s, t, 2);
}
/*Output on my computer is:
Hiy Press any key to continue...
*/
The following code I wrote I think will do what the author is trying to do.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <cstring>
usingnamespace std;
int main(void)
{
char s[7]= "Say ";
char t[]="Hi";
cout << strcat(s, t);
}
/*Output on my computer is:
Say HiPress any key to continue...
*/