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

时间:2016-02-10 17:38:05

标签: c++ arrays string type-conversion

如何将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*)’

2 个答案:

答案 0 :(得分:6)

这是一种方式:

#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;
}

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

答案 1 :(得分:0)

也可以使用reinterpret_cast:

int main() {
    std::string sample = ".1.3.6.1.4";
    auto uCharArr = reinterpret_cast<unsigned char*>(sample.c_str());
}