How to copy a string into a char array in C++ without going over the buffer

前端 未结 11 936
Happy的楠姐
Happy的楠姐 2020-12-08 03:13

I want to copy a string into a char array, and not overrun the buffer.

So if I have a char array of size 5, then I want to copy a maximum of 5 bytes from a string in

相关标签:
11条回答
  • 2020-12-08 03:30

    This is exactly what std::string's copy function does.

    #include <string>
    #include <iostream>
    
    int main()
    {
    
        char test[5];
        std::string str( "Hello, world" );
    
        str.copy(test, 5);
    
        std::cout.write(test, 5);
        std::cout.put('\n');
    
        return 0;
    }
    

    If you need null termination you should do something like this:

    str.copy(test, 4);
    test[4] = '\0';
    
    0 讨论(0)
  • 2020-12-08 03:32

    Use function strlcpybroken link, and material not found on destination site if your implementation provides one (the function is not in the standard C library), yet it is rather widely accepted as a de-facto standard name for a "safe" limited-length copying function for zero-terminated strings.

    If your implementation does not provide strlcpy function, implement one yourself. For example, something like this might work for you

    char *my_strlcpy(char *dst, const char *src, size_t n)
    {
      assert(dst != NULL && src != NULL);
    
      if (n > 0)
      {
        char *pd;
        const char *ps;
    
        for (--n, pd = dst, ps = src; n > 0 && *ps != '\0'; --n, ++pd, ++ps)
          *pd = *ps;
    
        *pd = '\0';
      }
    
      return dst;
    }
    

    (Actually, the de-facto accepted strlcpy returns size_t, so you might prefer to implement the accepted specification instead of what I did above).

    Beware of the answers that recommend using strncpy for that purpose. strncpy is not a safe limited-length string copying function and is not supposed to be used for that purpose. While you can force strncpy to "work" for that purpose, it is still akin to driving woodscrews with a hammer.

    0 讨论(0)
  • std::string my_string("something");
    char* my_char_array = new char[5];
    strncpy(my_char_array, my_string.c_str(), 4);
    my_char_array[4] = '\0'; // my_char_array contains "some"
    

    With strncpy, you can copy at most n characters from the source to the destination. However, note that if the source string is at most n chars long, the destination will not be null terminated; you must put the terminating null character into it yourself.

    A char array with a length of 5 can contain at most a string of 4 characters, since the 5th must be the terminating null character. Hence in the above code, n = 4.

    0 讨论(0)
  • 2020-12-08 03:35
    char mystring[101]; // a 100 character string plus terminator
    char *any_input;
    any_input = "Example";
    iterate = 0;
    while ( any_input[iterate] != '\0' && iterate < 100) {
        mystring[iterate] = any_input[iterate];
        iterate++;
    }
    mystring[iterate] = '\0';
    

    This is the basic efficient design.

    0 讨论(0)
  • 2020-12-08 03:39

    i think snprintf() is much safe and simlest

    snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );
    

    null character is append it end automatically :)

    0 讨论(0)
  • 2020-12-08 03:40

    If you always have a buffer of size 5, then you could do:

    std::string s = "Your string";
    char buffer[5]={s[0],s[1],s[2],s[3],'\0'};
    

    Edit: Of course, assuming that your std::string is large enough.

    0 讨论(0)
提交回复
热议问题