C++ std::string InputIterator 代码到 C 代码

标签 c++ c string

我发现一些 C++ 代码完全可以满足我的需要,但是我需要用 C 编写它,但我不知道如何用 C 编写它,所以我希望有人能帮助我。

C++代码是:

std::string value( (const char *)valueBegin, (const char *)valueEnd );

这是使用 string::string 构造函数:

template<class InputIterator> string (InputIterator begin, InputIterator end);

谁能帮我把它转换成 C 代码?

谢谢!

最佳答案

// Get the number of characters in the range
size_t length = valueEnd - valueBegin;

// Allocate one more for the C style terminating 0
char *data = malloc(length + 1);

// Copy just the number of bytes requested
strncpy(data, valueBegin, length);

// Manually add the C terminating 0
data[length] = '\0';

关于C++ std::string InputIterator 代码到 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2253825/

相关文章:

c++ - 为什么在以下代码中调用析构函数?

c++ - 增加初始化列表中使用两次的变量 - 未定义的行为?

c# - 具有特定要求的拆分字符串

c++ - 使用 C 风格的字符串有哪些缺点?

c# - 替换字符串中的字符

c++ - calloc 的等效代码

c++ - 如何防止在构造函数或析构函数中调用虚函数?

c++ - 获取 GDB 便利变量中保存的值的符号信息

c++ - 我真的必须链接 Ws2_32.lib 吗?

c - 使用优化时,gcc 不在符号表中包含外部变量