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

前端 未结 11 946
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: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.

提交回复
热议问题