0

It's possible to put something in to an unique_ptr that is pointing to a char array, something like this:

#include <iostream>
#include <memory>
#define LEN 100
using std::cout, std::cin;

int main() {
    std::unique_ptr<char[]> ptr {new char[LEN]};

    cout << "Enter a word: \n";
    cin >> ptr;
}

I tried with this and also with getline but doesn't work

1 Answers1

0

It depends on what kind of an array you want. For dynamically sized data, simply use a std::string. For something statically sized, a3 below wins in terms of efficiency, a simple buffer on the stack. It doesn’t use a unique_ptr, but it’s unclear why the exercise forces you to use dynamic allocation for no good reason.

#include <array>
#include <cstdint>
#include <iostream>
#include <memory>

namespace {
constexpr size_t LEN{100};
}

int main() {
  std::unique_ptr a1{std::make_unique<char[]>(LEN)};
  std::unique_ptr a2{std::make_unique<std::array<char, LEN>>()};
  std::array<char, LEN> a3;

  std::cout << "Enter a word: \n";
  std::cin.getline(a1.get(), LEN);
  std::cout << "Enter a word: \n";
  std::cin.getline(a2->data(), LEN);
  std::cout << "Enter a word: \n";
  std::cin.getline(a3.data(), LEN);

  std::cout << a1.get() << '\n' << a2->data() << '\n' << a3.data() << '\n';
}
Andrej Podzimek
  • 2,409
  • 9
  • 12