gpt4 book ai didi

c++ - 如何将 std::string 复制到 unsigned char 数组?

转载 作者:太空狗 更新时间:2023-10-29 20:23:00 25 4
gpt4 key购买 nike

如何将 std::string(示例)复制到 unsigned char 数组(陷阱)?

int main() {
unsigned char trap[256];
std::string sample = ".1.3.6.1.4";
strcpy(trap,sample.c_str());
std::cout << trap << std::endl;
}

以上代码抛出错误:

time.cpp: In function ‘int main()’:
time.cpp:20: error: invalid conversion from ‘unsigned char*’ to ‘char*’
time.cpp:20: error: initializing argument 1 of ‘char* strcpy(char*, const char*)’

最佳答案

这是一种方法:

#include <algorithm>
#include <iostream>

auto main() -> int
{
unsigned char trap[256];
std::string sample = ".1.3.6.1.4";
std::copy( sample.begin(), sample.end(), trap );
trap[sample.length()] = 0;
std::cout << trap << std::endl;
}

额外检查缓冲区是否足够大可能是个好主意。

关于c++ - 如何将 std::string 复制到 unsigned char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35322150/

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