creating dynamic array of string c++

46,605

Solution 1

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"));
}

Solution 2

use std::vector<string> or std::list<string> over hand rolling it.

Solution 3

I think that should be:

std::cin >> collection[i];
Share:
46,605
Abdul Samad
Author by

Abdul Samad

Updated on April 02, 2020

Comments

  • Abdul Samad
    Abdul Samad about 4 years

    I am struct to a very basic question. I want to create dynamically an array of string in c++.

    How can I do that ?

    This is my attempt:

    #include <iostream>
    #include <string>
    int main(){
        unsigned int wordsCollection = 6;
        unsigned int length = 6;
    
        std::string *collection = new std::string[wordsCollection];
        for(unsigned int i = 0; i < wordsCollection; ++i){
            std::cin>>wordsCollection[i];
        }
        return 0;    
    }
    

    But it giving the following error

    error C2109: subscript requires array or pointer type
    

    What's the error ?

    And also if I'am getting input number from user, from std::cin can I create an array of that size statically ?

  • cnicutar
    cnicutar over 12 years
    But the real problem is that wordsCollection should be collection.
  • Abdul Samad
    Abdul Samad over 12 years
    Oh my God how silly i am... Any how thanks... can you tell me the answer for my second question that can i create a static array of that
  • Lea Hayes
    Lea Hayes over 12 years
    I agree, but if you choose to go ahead with new std::string do not forget to delete[] collection when you are done. It is a good idea to ensure that for every new you have a delete
  • rerun
    rerun over 12 years
    You can't create an array of any size where you get the size at runtime. You can create a pointer to a buffer of n elements that acts like an array but you will have to delete it. Thats one of the many reason using the stl containers are preferable.