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 ?
You meant to type:
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: