When I try to run this program I get an error that halts the program and says, "Vector subscript out of range"
Any idea what I'm doing wrong?
#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
//(int argc, char* argv[]
int main()
{
fstream bookread("test.txt");
vector<string> words;
bookread.open("test.txt");
if(bookread.is_open()){
cout << "opening textfile";
while(bookread.good()){
string input;
//getline(bookread, input);
bookread>>input;
//string cleanedWord=preprocess(input);
//char first=cleanedWord[0];
//if(first<=*/
//cout << "getting words";
//getWords(words, input);
}
}
cout << "all done";
words[0];
getchar();
}
A vector subscript is an integer array expression of rank one, designating a sequence of subscripts that correspond to the values of the elements of the expression. A vector subscript can be a real array expression of rank one in XL Fortran.
vector subscript out of range means "you asked for an element from the vector, but the vector is not of that size". e.g. vector<int> vec; vec.push_back(42); vec[1] // oops, 42 is vec[0]
Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.
You never insert anything into the words vector
, so the line words[0];
is illegal, because it accesses the first element of it, which does not exist.
I don't see where you're pushing anything on to the vector. If the vector is empty, subscript 0 would be out of range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With