20 ) { strcpy(copy, array....); what i nee...">

Strcpy string array

char copy, array[20] printf("enter ..."): scanf("%s", array); if (strlen(array) > 20 ) { strcpy(copy, array....); 

what i need to do to make it only capture the first 20 characters if the input is longer than 20 characters

+4
source share
7 answers

Use strncpy instead of strcpy . That is all there is. (Note: strncpy does not nul-terminate the destination string if it reaches its limit.)

EDIT: I have not read your program enough. You lose already when you call scanf if user input is longer than 20 characters. You should call fgets instead. (Personally, I think * scanf should never be used - this is just the tip of the iceberg, as they cause problems.) In addition, copy takes place only for one character, not for twenty; but I'm going to assume a typo on your part.

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

The problem is resolved.

+5
source

Your question is not clear, since the code is little or no sense. Your input cannot be longer than 20 characters, since the receiving array is only 20 characters. If the user types more, your program will generate undefined behavior. So, the main problem here is not the copy limitation, but the input limitation.

However, your question seems to be related to string copying with a limited length. If this is what you need, then, unfortunately, there is no special function in the standard library for this purpose. Many implementations provide a non-standard strlcpy function that does just that. So check if your implementation of strlcpy implements or implements your own strlcpy yourself.

In many cases, you can use strncpy tips in such cases. Although strncpy can be outperformed for this purpose, strncpy not really intended to be used that way. Using strncpy as a function to copy strings of limited length is always a mistake. Avoid this.

+3
source

Also, you don't need to use strcpy to read just 20 characters (and you don't need 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'; 

Remember to declare the array as char array[21] to ensure that '\ 0' will be included.

+1
source

Use strncpy . Make sure null completes the assignment.

0
source
  strncpy (copy, array, 20); 

does the trick. Exxcept if the string would not be zero, if it would be a> 20 characters!

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

0
source

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

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

Source: https://habr.com/ru/post/1341370/


All Articles