如何将字符串复制到C ++中的一个char数组,而不超过缓冲区 [英] How to copy a string into a char array in C++ without going over the buffer

查看:139
本文介绍了如何将字符串复制到C ++中的一个char数组,而不超过缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



因此,如果我有一个大小为5的char数组,那么我想要一个字符串数组,而不是超过缓冲区。



这样做的代码是什么?

解决方案

首先, strncpy 几乎肯定不是你想要的。 strncpy 是为了相当特殊的目的而设计的。它在标准库中几乎完全是因为它已经存在,而不是因为它通常是有用的。



可能是最简单的方法来做你想要的东西像:

  sprintf(buffer,%.4s,your_string.c_str()); 

strncpy 不同,将被NUL终止,但是如果源比指定的短,则不填充目标中的额外数据(虽然当目标长度为5时后者不是主要问题)。


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 into it.

what's the code to do that?

解决方案

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());

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天全站免登陆