Creating a dynamic array of C ++ strings

I am building a very simple question. I want to create a dynamically array of strings in C ++.

How can i do this?

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 this gives the following error:

 error C2109: subscript requires array or pointer type 

What mistake?

And also, if I get the input number from the user, from std::cin can I create an array of this size statically?

+6
source share
6 answers

You intended to print:

 std::cin>>collection[i]; 

And you also need delete[] collection (or you skip this memory).

Better to use std::vector<std::string> collection; and generally avoid using a raw pointer:

 #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")); } 
+9
source

use std::vector<string> or std::list<string> , turning it over manually.

+10
source

I think it should be:

 std::cin >> collection[i]; 
+1
source

I think this is a simple typo. std::cin>>wordsCollection[i] should be std::cin>>collection[i] .

0
source

You get this error because you are trying to access int elements (i.e. wordsCollection ), and not an int array (i.e. collection ). What should you write?

 std::cin>>collection[i] 
0
source

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; } 
0
source

Source: https://habr.com/ru/post/906510/


All Articles