strcpy string array

落爺英雄遲暮 提交于 2019-12-10 17:32:04

问题


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);


来源:https://stackoverflow.com/questions/5122882/strcpy-string-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!