Out of range code index error, C ++

When I try to run this program, I get an error message that stops the program and says: "Vector index 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(); } 
+6
c ++ file vector
source share
4 answers

You never insert anything into the words vector , therefore the string words[0]; It is illegal because it refers to its first element, which does not exist.

+7
source share

I don’t see where you click on the vector. If the vector is empty, index 0 will be out of range.

+2
source share

It seems like your program never comes close to adding anything to a vector, usually done with push_back() , so when you execute words[0] you get a subscript out of range error.

Before accessing it, you need to check the size of the vector.

Try the following:

 for(vector<string>::const_iterator it=words.begin(), end=words.end(); it!=end; ++it){ cout << *it << ' '; } 
0
source share

Can you attach a version of the code in which you actually click the buttons on the vector. It is impossible to debug the problem if the code for which it is playing is not available for viewing.

0
source share

All Articles