我如何将这个std :: string转换为std :: basic字符串?

时间:2018-10-27 01:16:30

标签: c++ string std memcpy strcpy

目前,我有一个名为std:::string的{​​{1}},可以通过以下过程获得:

cipher_line

现在,我希望能够从string str_cipher_line; // Get the Offline Mount Point ifstream ifs1; ifs1.open(offlineMountPoint.c_str()); if (ifs1.is_open()) { getline(ifs1, str_cipher_line); } else { cout << "unable to open file" << endl; return 1; } ifs1.close(); 获得一个secure_stringcipher_line的定义如下:

secure_string

我不知道该怎么做。我应该雇用typedef std::basic_string<char, std::char_traits<char>, zallocator<char> > secure_string; 还是memcpy

1 个答案:

答案 0 :(得分:1)

使用std::basic_string iterator constructor(在cppreference上为6)从secure_stringstd::copy构造。反之亦然。

#include <iostream>

template <typename T>
struct some_other_allocator : std::allocator<T>{};

using other_string = std::basic_string<char, std::char_traits<char>, some_other_allocator<char>>;

int main() {
    other_string string1("hello");

    //using std::string constructor
    std::string string2(string1.begin(),string1.end());

    std::string string2_copy;
    //using std::copy
    std::copy(string1.begin(),string1.end(),std::back_inserter(string2_copy));

    std::cout << string1 << std::endl;
    std::cout << string2 << std::endl;
    std::cout << string2_copy << std::endl;
    return 0;
}

Demo