Hunter Hunter - 1 year ago 133
C++ Question

C++ How to fill a vector of undefined size with strings?

I'm trying to get a user-inputted string to be split up and stored in a vector character by character. However, when the string is inputted and entered, I get this error:

Debug Assertion Failed!

Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll

File: c:\program files (x86)\microsoft visual studio 14.0\vc\include\vector

Line: 1234

Expression: vector subscript out of range

I've tried researching vectors to see if I'm implementing it correctly but from what I can see it appears I am.

Here is my code:

#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>
#include <vector>

using namespace std;

void rovarspraket(); //declaration because I like to put my functions after main()

int main() {
rovarspraket(); //function call

return 0;

void rovarspraket() { //the function
string sText; //string that will be inputted
vector<string> vText; //vector that sText will go into

cout << "Input text to be encoded to Rovarspraket: ";
getline(cin, sText); //gimme dat sText

cout << "\n\n"; //pretty formatting, just ignore

for (int i = 0; i < sText.length(); ++i) {
vText[i] = sText[i]; //slap that character into the vector
cout << vText[i] << endl; //just to test what was actually happening

Answer Source

Sam Varshavchik said it already, I'd like to explain it a little bit more though. But basically your trying to assign the first element of a vector to something else, but the issue is that your vector is empty, so there's no element to assign! Use .push_back() to add an element to the end of the vector. So your "for" loop should look like this:

for (int i = 0; i < sText.length(); ++i) {
    cout << vText[i] << endl;