Reputation: 5918
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 ?
Upvotes: 7
Views: 57212
Reputation: 141780
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"));
}
Upvotes: 11
Reputation: 2914
You're getting this error because you're trying access the elements of an int (i.e. wordsCollection
), not an array of int (i.e. collection
). What you should be writing is
std::cin>>collection[i]
Upvotes: 0
Reputation: 160
Try the following:
#include <vector>
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::vector<std::string> myStrings;
myStrings.push_back(std::string("string1"));
myStrings.push_back(std::string("string2"));
std::vector<std::string>::iterator iter = myStrings.begin();
std::vector<std::string>::iterator end = myStrings.end();
while(iter != end)
{
std::cout << (*iter) << std::endl;
++iter;
}
return 0;
}
Upvotes: 0
Reputation: 308111
I think it's a simple typo. std::cin>>wordsCollection[i]
should be std::cin>>collection[i]
.
Upvotes: 0
Reputation: 25495
use std::vector<string>
or std::list<string>
over hand rolling it.
Upvotes: 10