strcpy string array

2019-06-25 18:28发布

问题:

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

回答1:

Use strncpy instead of strcpy. 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 calling fgets 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.



回答2:

char array[20+1];
scanf("%20s", array);

Problem solved.



回答3:

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 provides strlcpy or implement your own strlcpy yourself.

In many cases you might see advices to use strncpy in such cases. While it is possible to beat strncpy into working for this purpose, in reality strncpy is not intended to be used that way. Using strncpy as a limited-length string copying function is always an error. Avoid it.



回答4:

Alternatively, you don't need to use strcpy to read just 20 characters (and you won't have to include strings.h):

char c;
for( i = 0; i < 20; i++ ) {
    c = getchar();
    if (c != '\n') array[i] = c;
    else break;
}
array[i+1] = '\0';

Don't forget to declare array as char array[21] to make sure '\0' will be included.



回答5:

 strncpy (copy, array, 20);

does the trick. Exxcept the string would NOT be null-terminated if it was >20 chars!

http://www.cplusplus.com/reference/clibrary/cstring/strncpy/



回答6:

Use strncpy. Make sure to null terminate the destination.



回答7:

You need to change your scanf() call, not your strcpy() call:

char copy[20], array[20];
printf("enter....");
scanf(%20s",array); // read a maximum of 20 characters
strcpy(copy, array);


标签: c strcpy