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 数组中
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
