2011-03-01 82 views
6

當我嘗試運行這個程序,我得到的是暫停程序,並說,「矢量下標越界」矢量下標超出範圍錯誤,C++

任何想法,我做錯了錯誤?

#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(); 
} 
+0

http://stackoverflow.com/q/43108052/7276612[Doesn't似乎一直工作。我在哪裏錯了?] [1] – DamienArt1234 2017-03-30 20:30:34

回答

7

你永遠不插入任何東西的話vector,太行words[0];是非法的,因爲它訪問它的第一個元素,它不存在。

+0

我在while循環中添加了words.push_back(輸入),並且仍然收到錯誤 – charli 2011-03-01 23:16:37

+0

如果程序確實已經到達此行,請使用附加的調試器進行檢查。我不這麼認爲。 – 2011-03-01 23:17:59

+0

它說錯誤是行779?但是程序顯然不那麼長 – charli 2011-03-01 23:23:29

2

我沒有看到你在向哪個方向推動任何東西。如果矢量爲空,則下標0將超出範圍。

0

看起來你的程序從來不會爲向量添加任何東西,通常使用push_back()來完成,所以在運行時words[0]會產生你的subscript out of range錯誤。

您應該在訪問它之前檢查向量的大小。

試試這個:

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

你能請附上代碼的版本,你實際上的push_back的向量的字符串。它不可能調試這個問題,除非重現的代碼可用於審查。