如何在不越过缓冲区的情况下将字符串复制到 C++ 中的 char 数组中
我想将一个字符串复制到一个 char 数组中,而不是超出缓冲区.
I want to copy a string into a char array, and not overrun the buffer.
所以如果我有一个大小为 5 的 char 数组,那么我想从一个字符串中复制最多 5 个字节.
So if I have a char array of size 5, then I want to copy a maximum of 5 bytes from a string into it.
执行此操作的代码是什么?
what's the code to do that?
推荐答案
首先,strncpy
几乎可以肯定不是你想要的.strncpy
是为相当特定的目的而设计的.它在标准库中几乎完全是因为它已经存在,而不是因为它通常很有用.
First of all, strncpy
is almost certainly not what you want. strncpy
was designed for a fairly specific purpose. It's in the standard library almost exclusively because it already exists, not because it's generally useful.
做你想做的最简单的方法可能是:
Probably the simplest way to do what you want is with something like:
sprintf(buffer, "%.4s", your_string.c_str());
与 strncpy
不同,这保证结果将以 NUL 终止,但如果源比指定的短,则不会在目标中填充额外数据(尽管后者不是主要问题当目标长度为 5).
Unlike strncpy
, this guarantees that the result will be NUL terminated, but does not fill in extra data in the target if the source is shorter than specified (though the latter isn't a major issue when the target length is 5).
相关文章