-1

Currently I have a std:::string called cipher_line that I get from the process of:

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();  

Now I want to be able to get a secure_string from cipher_line. secure_string is defined below:

typedef std::basic_string<char, std::char_traits<char>, zallocator<char> > secure_string;

I don't understand how to do this. Should I employ memcpy or strcpy?

SDG
  • 2,260
  • 8
  • 35
  • 77
  • 4
    Neither. Use the constructor that takes a beginning and an ending iterator, and pass in `std::string`'s `begin()`, and `end()`. – Sam Varshavchik Oct 27 '18 at 01:22
  • yeah, could you elaborate on that as an answer @SamVarshavchik – SDG Oct 27 '18 at 01:26
  • This doesn’t address the question, but get in the habit of initializing objects with meaningful values rather than default constructing them and then changing them. That is, change `ifstream ifs1; ifs1.open(whatever);` to `ifstream ifs1(whatever);`. And you don’t need to call `ifs1.close()`. The destructor will do that. – Pete Becker Oct 27 '18 at 01:35
  • @PeteBecker Thanks, good advice is always welcome! – SDG Oct 27 '18 at 01:48

1 Answers1

1

Use std::basic_string iterator constructor (6 on cppreference) to construct from secure_string or std::copy. The same applies the other way around.

#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

rmawatson
  • 1,909
  • 12
  • 20
  • Your answer code shows how to construct `secure_string` (or `other_string` in your code) from a string literal, but I think the questioner wanted to see how to construct it from `std::string`: `secure_string myString{str_cipher_line.begin(), str_cipher_line.end()};` – stackprotector Oct 01 '20 at 08:49