gpt4 book ai didi

c++ - 从 std::string 复制到 char 数组并以 null 终止结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:53:56 24 4
gpt4 key购买 nike

我有一个 Visual Studio 2008 C++03 应用程序,我想在其中从 std::string 复制到 char 数组,但我需要 char 数组以 null 终止,即使它必须截断字符串才能这样做.

例如,这可以按需要工作:

inline void CopyAndNullTerminate( const std::string& source, 
char* dest,
size_t dest_size )
{
source.copy( dest, dest_size );
using std::min;
char* end = dest + min( dest_size - 1, source.size() );
*end = '\0';
}

int main()
{
enum{ MAX_STRING_SIZE = 15 };
char dest[ MAX_STRING_SIZE ];
std::string test = "This is a test";

CopyAndNullTerminate( test, dest, MAX_STRING_SIZE );

assert( strcmp( test.c_str(), dest ) == 0 );
return 0;
}

示例:http://ideone.com/0EBYb

是否有更短、更有效的方法来做到这一点?

谢谢

最佳答案

是的,使用 strncpy , 在 cstring 中定义:

void copyString(const std::string& input, char *dst, size_t dst_size)
{
strncpy(dst, input.c_str(), dst_size - 1);
dst[dst_size - 1] = '\0';
}

请注意,对于 std::string 的某些实现(正如@K-ballo 所指出的),这可能更短,但效率较低。这是因为 std::string 不能保证使用 C 风格字符串实现,尽管在大多数情况下可能是这种情况。

关于c++ - 从 std::string 复制到 char 数组并以 null 终止结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10903181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com