creating dynamic array of string c++

You meant to type:

std::cin>>collection[i];

And you also need to delete[] collection (or you’ll leak this memory).

It would be better use std::vector<std::string> collection; and avoid the raw pointer usage altogether:

#include <iterator>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    const unsigned int wordsCollection = 6;

    std::vector<std::string> collection;
    std::string word;
    for (unsigned int i = 0; i < wordsCollection; ++i)
    {
        std::cin >> word;
        collection.push_back(word);
    }

    std::copy(collection.begin(),
              collection.end(),
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

Leave a Comment