You can't create an element of a vector using the []
indexing operator; your line arr[i] = s;
is trying to assign a string to an element that doesn't (yet) exist.
There are several ways around this: first, you could use the push_back
function to add a new element to the end of the vector, in each loop; second, you could use the resize
member to pre-allocate a specified number of elements (which you can then use in the arr[i] = s;
line); third - and perhaps simplest - you can 'pre-allocate' the elements of the vector by specifying the number of elements in the declaration (constructor), like this:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string> // Need this for the "getline()" function definition
using namespace std;
int main()
{
size_t n; // Indexes and operations on std::vector use "size_t" rather than "int"
cin >> n;
cin.ignore(1); // Without this, there will be a leftover newline in the "cin" stream
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // More precise, actually!
vector<string> arr(n);
// arr.resize(n); // Alternative to using 'n' in constructor
for (size_t i = 0; i < n; i++) {
string s;
getline(cin, s);
arr[i] = s;
}
for (auto s : arr) cout << s << endl; // Just to confirm the input values
return 0;
}
There are also a few other issues in your code that I have 'fixed' and commented on in the code I posted. Feel free to ask for further clarification and/or explanation.
EDIT: On the use of the cin.ignore(1);
line I added, see Why does std::getline() skip input after a formatted extraction? (and the excellent answers given there) for more details.