2014-10-08 45 views
-2

在將文件abc.txt叫,我有輸入以下文本:C++矢量subsctript超出範圍

sample text 
sample text 
sample text 
sample text 
sample text 

首先我創建的變量(名稱爲文本),用於保存文本的從文件中讀取。然後程序讀取文件abc.txt。我創建了名爲ArrSent的矢量,用於保存文件abc.txt中的每一行。循環結束後,程序關閉文件abc.txt。然後程序必須輸出ArrSent中的所有句子給screnn。我有這樣的問題:程序結束後,出現警告消息:vector下標超出範圍。我不知道爲什麼..

#include<iostream> 
#include<string> 
#include<fstream> 
#include<vector> 

using namespace std; 

void function() 
{ 
    string text;//variable to save text from file 
    ifstream myfile("abc.txt");//reading from file colled abc.txt 




    vector<string> ArrSent; 

    if (myfile.is_open()) 
    { 
     //cout <<"myplik.good()= "<< myfile.good() << endl; 

     while (myfile.good()) 
     { 
       getline(myfile, text); 
       ArrSent.push_back(text); 
     } 


     myfile.close(); 
    } 
    for (int i = 0; i <= ArrSent.size(); i++) 
    { 
     cout << ArrSent[i] << endl; 
    } 

} 


int main() 
{ 
    function(); 
    system("pause"); 
    return 0; 
} 
+1

'is_open()'和'good()'是完全沒有意義的,而'getline'後面的'push_back'是平坦的,因爲你忽略了返回值。 – 2014-10-08 21:18:29

+1

請擺脫[系統(「暫停」)](http://www.gidnetwork.com/b-61.html) - 它是危險的和不可移植的。 – 2014-10-08 21:22:51

回答

4

這是錯在這裏

for (int i = 0; i <= ArrSent.size(); i++) 
{ 
    cout << ArrSent[i] << endl; 
} 

應該

for (int i = 0; i < ArrSent.size(); i++) 
{ 
    cout << ArrSent[i] << endl; 
} 

其原因是,在C/C++,矢量/陣列爲零根據。也就是說,如果你有一個向量,my_vector,大小爲10,它就像my_vector [0],my_vector [1],... my_vector [9]一樣。沒有my_vector [10]。

一種更好的方式來遍歷它,可以是(C++ 11)

for (const auto & v : ArrSent) 
{ 
    cout << v << endl; 
} 

for (vector<string>::const_iterator i = ArrSent.begin(); i != ArrSent.end(); ++i) 
    cout << *i << endl; 

正如WhozCraig指出的那樣,用於讀取的while循環也馬車,一個更好的版本可能是

while (getline(myfile, text)) 
    { 
     ArrSent.push_back(text); 
    } 

A Word About function

值得注意的是:你的函數名是function。雖然這可能是描述性的,但您應該知道標準庫標頭可以自由包含其他標準庫標頭(並且非常頻繁地就是這樣做的)。標準庫中的一個這樣的頭文件是<functional>,它聲明,如運氣一樣,std::function

你爲什麼在意?因爲您的using namespace std;std中的所有內容全部公開,並且沒有名稱空間限定符要求,包括潛在的std::function(無論您是否包含<functional>)。

這意味着,儘管這仍然會編譯:

void function() 
{ 
    // .. stuff 
} 

這可能不是:

int main() 
{ 
    function(); // HERE 
    //... other stuff 
} 

這個不知道是否你打電話功能或試圖實例化一個單類型std::function<>(它不能這樣做,因爲沒有描述模板參數)。結果可能是含糊

您可以在您的main()使用::function();解決這個問題,但如果你得到了發展,在整個std庫通過using namespace std;不啜的習慣,這將是更好的,和/或沒有使用常見的類型/ IDS的名字從標準庫。

+1

事實上,這應該是使用迭代器或範圍 - 枚舉首先。 – WhozCraig 2014-10-08 21:17:26

+0

你是對的。我會更新這個答案 – 2014-10-08 21:18:00

+1

也可以修復他們'getline'在你的時候工作的錯誤假設。寫入的讀取循環只比「while(!std :: cin.eof())」稍微好一些,這是[幾乎總是錯誤的](http://stackoverflow.com/questions/5605125/why-是-iostreameof-內,一個循環條件考慮的,是錯誤的)。 – WhozCraig 2014-10-08 21:19:38