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

前端 未结 11 935
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:47

    std::string str = "Your string";
    char buffer[5];
    strncpy(buffer, str.c_str(), sizeof(buffer)); 
    buffer[sizeof(buffer)-1] = '\0';
    

    The last line is required because strncpy isn't guaranteed to NUL terminate the string (there has been a discussion about the motivation yesterday).

    If you used wide strings, instead of sizeof(buffer) you'd use sizeof(buffer)/sizeof(*buffer), or, even better, a macro like

    #define ARRSIZE(arr)    (sizeof(arr)/sizeof(*(arr)))
    /* ... */
    buffer[ARRSIZE(buffer)-1]='\0';
    

提交回复
热议问题