如何在不越过缓冲区的情况下将字符串复制到 C++ 中的 char 数组中 [英] How to copy a string into a char array in C++ without going over the buffer

查看:25
本文介绍了如何在不越过缓冲区的情况下将字符串复制到 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 数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆