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