How can I copy a certain number of characters in a string onto another string?
If I have the following:
char fname, lname, nemp,*name,*ptr;
name= Archie S. Andrews
name[strlen(name)-1]='\0'; // to append to terminate string up to this point
By using strrchr I can point to '.' with the address stored in *ptr, and then copy its contents to lname using strcpy.
But how can I use strncpy in such a way that fname will contain only the string "Archie"?
I have tried the code below:
ptr-=2; // this points to S
strcpy(nemp,ptr); // nemp now contains "S. Andrews"
strncpy(fname,name,(strlen(name) - strlen(nemp));
This code prints out "Archie" but followed by some garbage characters and longer than name. One possible solution to this is to append a '\0' at the end of "Archie". But what if I do not know the actual length of the first name and I only got it from a file?
If you know of another workaround aside from storing the characters one at a time to another character array, please let me know. I know that storing it by character is possible, but it will have longer code. Also, I just wish to use pointers to manipulate strings ^^