How to copy a string into a char array in C++ without going over the buffer(如何在不越过缓冲区的情况下将字符串复制到 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).
这篇关于如何在不越过缓冲区的情况下将字符串复制到 C++ 中的 char 数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不越过缓冲区的情况下将字符串复制到 C++ 中的 char 数组中
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
