#include <iostream>
using namespace std
#include <string.h>
int main(){
char token[] = "some random string";
char c[23];
strcpy( c, token);
strncpy(c, token, 5);
c[strlen(c)] = '\0';
cout<<c;
return 0 ;
}
My output is: some random string. But I expect it to be: some. Can anyone please explain why it is behaving like this?
I think your output should be “some random string”, because your two lines of code do nothing, see the comment.
If you want to output “some”, you could do this:
strncpy() doesn’t automatically add trailing ‘\0’ to dest string. If the source string length is bigger than len (3rd argument of strncpy), then len characters copied to dest without trailing ‘\0’. So you have to give a trailing ‘\0’ explicitly by code.