char copy, array[20]
printf("enter ..."):
scanf("%s", array);
if (strlen(array) > 20 )
{
strcpy(copy, array....);
what would I need to do to make it only grab the first 20 character if the input is more then 20 character long
You need to change your scanf() call, not your strcpy() call:
Use strncpy. Make sure to null terminate the destination.
Problem solved.
Use
strncpy
instead ofstrcpy
. That's all there is to it. (Caution:strncpy
does not nul-terminate the destination string if it hits its limit.)EDIT: I didn't read your program carefully enough. You lose already at the
scanf
call if user input is longer than 20 characters. You should be callingfgets
instead. (Personally I think *scanf should never be used - this is only the tip of the iceberg as far as problems they cause.) Furthermore,copy
has room for only one character, not twenty; but I'm going to assume that's a typo on your part.Your question is not clear, since the code makes little or no sense. Your input cannot be longer than 20 characters since the receiving array is only 20 characters. If the user inputs more, your program will produce undefined behavior. So, the main problem here is not limiting the copy, but rather limiting the input.
However, your question seems to be about limited-length string copying. If that's what you need, then unfortunately there no dedicated function in standard library for that purpose. Many implementation provide the non-standard
strlcpy
function that does exactly that. So, either check if your implementation providesstrlcpy
or implement your ownstrlcpy
yourself.In many cases you might see advices to use
strncpy
in such cases. While it is possible to beatstrncpy
into working for this purpose, in realitystrncpy
is not intended to be used that way. Usingstrncpy
as a limited-length string copying function is always an error. Avoid it.does the trick. Exxcept the string would NOT be null-terminated if it was >20 chars!
http://www.cplusplus.com/reference/clibrary/cstring/strncpy/